Why am I getting 3 "Cross-Origin Request Blocked" messages - api

I have a Svelte application and I am trying to render data from the API but I keep on getting 3 error messages.
The code works properly on node but not on Svelte.
Below is the Svelte code:
<script lang="ts">
import { onMount } from "svelte";
let word = [];
onMount(async () => {
const response = await fetch(
"https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5",
{
method: "GET",
headers: {
"X-RapidAPI-Key": "KEY",
"X-RapidAPI-Host": "random-words5.p.rapidapi.com",
},
}
);
word = await response.json();
console.log(word);
});
</script>
<p>{word}</p>
And below are the error messages:
ross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://localhost:5173’).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://random-words5.p.rapidapi.com/getMultipleRandom?count=1&wordLength=5. (Reason: CORS request did not succeed). Status code: (null).
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
How do I get my code to render out the data from the API in Svelte?

The CORS issue occurs when you try to fetch a resource from a local environment, this is the case when you run your app in dev mode.
I use the CORS Unblock extension to fix the issue, give it a try.

Related

Axios triggering weird in React native app

Hello i have a weird thing going on,im using axios in order to send post-get http request for my app.The thing is that axios in my pc working good but in my laptop need console.log("") before axios request i dont know why.This happens in all my files.
It gives me this error : Possible Unhandled Promise Rejection (id : 0 ):
[Axios error: Request failed with statis code 404]
Here is my code :
function getProfile(){
try{
//console.log("") <-------------------------- Here i put it
axios.post(URL+'/checkData',
{
usernameCheckAXIOS : username,
passwordCheckAXIOS : password,
})
.then((response)=>{
console.log(response.data)
setProfile(response.data);
if(response.data.responseOfProfile == false){
Alert.alert("Access Dinied")
}
else{
navigation.navigate('Home')
}
})
}catch(error){}
}
If you are getting a “Possible unhandled promise rejection” warning in your React Native app, it means that a promise was rejected, but the rejection was not handled. Promises in JavaScript are used to handle asynchronous operations, and they can either be resolved or rejected.
axios.post(URL+'/checkData',
{
usernameCheckAXIOS : username,
passwordCheckAXIOS : password,
})
.then((response)=>{
//... your code
})
.chatch(error => console.log(error)) // <-- add this line
The HTTP 404 Not Found response status code indicates that the server cannot find the requested resource
so verify your URL, should be invalid because it cannot be found.
[Axios error: Request failed with statis code 404] is an error URL not found.
Are you sure that the url URL+'/checkData' is valid ?

Azure Search API throws CORS error even when CORS is enabled

I have an Azure search index called users that has CORS configured to * (for now) to allow all origins. When I make a GET request to it programmatically using fetch or axios, I get a CORS error:
Access to XMLHttpRequest at 'https://MY_SEARCH_SERVICE.search.windows.net/indexes/users/docs?api-version=2021-04-30-Preview&%24top=5&search=matt*&%24searchFields=name&%24select=id%2Cname%2Cemail&api-key=MY_API_KEY' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
However, if I put the same GET URL into a browser, it returns the list of expected results with no errors.
Here's my code (to run, create a Svelte app and put this in App.svelte or use the Svelte REPL. You must also have an Azure Search service set up, and you'll need to replace the placeholder variables MY_SEARCH_SERVICE and MY_API_KEY with your own, along with an index on which you want to try this):
<script lang="ts">
import { onMount } from "svelte";
const service = "https://MY_SEARCH_SERVICE.search.windows.net";
const index = "users";
const endpoint = `${service}/indexes/${index}/docs`;
const params = new URLSearchParams({
"api-version": "2021-04-30-Preview",
"api-key": "MY_API_KEY",
"$top": "5",
"$searchFields": "name,email",
"$select": "id,name,email"
});
const headers = new Headers({
"accept": "application/json"
});
onMount(async () => {
console.log(`${endpoint}?${params}`);
const response = await fetch(`${endpoint}?${params}`, {
headers: headers
});
console.log(await response.json());
});
</script>

Get shopify admin endpoint in axios in vue

How do you do this?
Use Admin API from Frontend(Headless Commerce) to get products from Shopify
<template>
<div>{{ data }}</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'ShopifyResult',
data () {
return {
data: null
}
},
mounted () {
const url = 'https://a-shopify-store.myshopify.com/admin/api/2021-10/checkouts.json';
axios({
method:'get',
url,
headers: {
"Content-Type": "application/json",
"X-Shopify-Access-Token": 'API_ADMIN_ACCESS_TOKEN_HERE',
},
}).then((result) => {
console.log(result.data)
}).catch(error => {
console.log(error)
});
}
}
</script>
This is what I get:
Access to XMLHttpRequest at
'https://a-shopify-store.myshopify.com/admin/api/2021-10/checkouts.json'
from origin 'http://localhost:8080' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. ShopifyResult.vue?4048:27 AxiosError
Why is CORS involved? I have a all the appropriate keys. How do you do this?
I also found
https://community.shopify.com/c/technical-q-a/vue-axios-get-requests-how-to-secure-apikey-and-apipass/td-p/689016
no answers.....
https://community.shopify.com/c/shopify-apis-and-sdks/using-apis-from-a-different-origin-domain/td-p/502781
Think of it this way:
Storefront API is a public API and the token for it is meant to be
used on the client side.
Admin API is a private API and the token is not meant to be shared
publicly. If you share this token to everyone by making requests from
the browser, they can potentially access private information about
your store, financial information, CUSTOMER information etc.
This could lead to both inconvenience to your customers as they would
be subject to fraud as well as you could run into legal issues if
someone decides to sue you because of it.
Hence, Shopify throws a CORS error when detecting that you use a
browser to send a request to a private API. While the CORS error might
not be the most appropriate response here, it is valid for them to
deny your request.
Hope that clarifies the issue for others encountering this error.

aws-sdk sendemail with angular 5. No 'Access-Control-Allow-Origin' header is present on the requested resource

I am trying to send email using aws-sdk's SES in my Angular application (Angular 5).
ses = new AWS.SES({
apiVersion: '2010-12-01',
accessKeyId:'<<access key>>',
secretAccessKey:'<<secretkey>>',
region: 'us-east-1',
endpoint: 'email-smtp.us-east-1.amazonaws.com',
sslEnabled: true
});
this.ses.sendEmail(this.params, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
console.log("Got error:", err.message);
console.log("Request:");
console.log(this.request.httpRequest);
console.log("Response:");
console.log(this.httpResponse);
} else {
console.log(data); // successful response
}
});
I am getting the below error.
Failed to load https://email-smtp.us-east-1.amazonaws.com/: Response
to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access.
I don't find a way to set the header values here.
There is one possible workaround to bypass the problem in local tests.
Using the chrome plugin https://chrome.google.com/webstore/search/access-contol-allow-origin.

make a HTTP Request from React-Redux from localhost

I am new to React Redux, and All I already did:
1) activate my backend server (localhost:5000)
2) activate my front-end server using npm start (localhost:8080)
3) I tried to dispatch action by using
this.props.dispatch({type: ActionTypes.FILE_UPLOAD_REQUEST, email: this.state.email, file: this.state.policyFile});
4) Using atlas-saga, and call my service function associated with the dispatch :
let result = yield call(Atlas.uploadFile, action.email, action.file);
5) define the function as :
export const uploadFile = (email, file) => {
return fetch(`${BASE_URL}/v1/files/${email}/policies`, {
method: 'POST',
headers:{} ,
body: {'file': file}
})
.then(response => response.json())
}
After I try to run a function at my react( a function that calls the dispatch), it gives me errors that they cannot found the route. This is the error message from the console.
Fetch API cannot load https://api-staging.autoarmour.co/v1/files/fakeemail#gmail.com/policies. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Yes, I did not create any reducer, just pure function that will upload a file. Thank you
I SOLVE IT, WOHOO!!!
The error message means that its not connected at the backend side at all. You need to make sure that it is connected. I solve it by connecting my redux to my react component. Thanks guys
Cheers!