Can't fetch API from React application - reactjs

I have built API in Google Cloud Function. The CORS error occurs when I try to fetch API directly. Although I added Access-Control-Allow-Origin, it failed.
The error:
'https://xxxxxxx.com' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
const apiURL = 'https://xxxxxxx.com'
const headers = new Headers();
headers.set("Content-type", "application/json");
headers.set("Access-Control-Allow-Origin", "*");
const createRes = await fetch(
`${apiURL}/testFetch`,
{
method: "POST",
headers: headers,
body: JSON.stringify({
test: "test"
}),
}
);

Access-Control-Allow-Origin is a response header. It should be a part of your response, not the request. Please ensure that your API returns the corresponding header.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Related

React Js Upload Images using Api

So I am trying to upload a file using React Js ant design upload component now the issue I am facing is that whenever I try to submit an image I received the following error:
Access to fetch at 'https://freeimage.host/api/1/upload' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I have attached the code that I have written to upload and handle file submissions.
I would try adding headers to the fetch inside your handleSubmission arrow function and stringify the body.
fetch('https://freeimage.host/api/1/upload', {
key: apiKey,
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData),
})
If you are using your backend as node js add following code to it
const cors = require("cors");
const corsOpts = {
origin: "*",
credentials: true,
};
app.use(cors(corsOpts));

Access to fetch at 'http://127.0.0.1:8000/blog/1' from origin 'http://localhost:3000' has been blocked by CORS policy

I'm trying to fetch some data from the Django Rest API. But browser throw cors policy error.
let headersList = {Accept: '*/*'}
fetch(url, {
method: 'GET',
headers: headersList,
})
.then(function (response) {
return response.json()
})
.then(function (data) {
console.log(data)
})
Access to fetch at 'http://127.0.0.1:8000/blog/1' from origin 'http://localhost:3000'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch
the resource with CORS disabled.
I also include cors-header in django api.
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True

ReactJS: access to fetch has been blocked by CORS policy

I am getting the following error in my ReactJS project:
"access to fetch has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
If an opaque serves your need set the request mode to 'no-cors' to fetch the resource with CORS disabled."
This is how I send requests to the backend:
export const sendRequest = async ( endpoint = '' ,
method = 'GET', body) => {
const response = await fetch(`${url}${endpoint}`, {
method,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
})
const data = await response.json();
return data;
}
I thought first that it is a backend problem but I checked there, found backend CORS Access is enabled for the same headers and client.
Any modifications should I do to the function above??
There an npm module called cors. You can install it in your backend. If you are using ExpressJS, you can just use cors as an middleware using app.use(cors()). With the equivalent header set in the request, it should work

Api call cause error 'Access-Control-Allow-Origin' header is present on the requested resource

I am trying to call an api but it is giving me following error :
Access to fetch at 'https://someapi.url/profile?FullName=sadaf&DateFrom=2000-01-01' from origin 'http://localhost:3000' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I am using react and the code is :
try {
let url = `https://someapi.url/profile?FullName=sadaf&DateFrom=2000-01-01`;
let response = await fetch(url,{
mode: 'cors', // no-cors,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
"Accept": 'application/json',
'Origin' : 'http://localhost:3000'
//'Content-Type': 'text/xml'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
});
this.setState(() => {
return {
searchResults : response
}
})
} catch (error) {
console.error(error);
}
please guide what to do
The error is due to CORS, there is nothing wrong with the front-end code.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses
additional HTTP headers to tell browsers to give a web application
running at one origin, access to selected resources from a different
origin.
To fix this issue, the server should set the CORS headers,
See here on how to enable CORS for your server
If your server is running express you need to set cors like this,
app.use(function(req, res, next) {
// update to match the domain you will make the request from
res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
or use the cors middleware for express

Fetch API cannot load, cors

In my React app I am trying to make a GET request from my heroku server to get a list of users:
https://blablabla.heroku.com/users
using the following request:
const sendSearch = fetch('/https://blablabla.heroku.com/users', {credentials: 'same-origin'})
function loadMyUsers(data) {
data.json().then((jsonData) => {
// console.log(jsonData)
})
}
sendSearch.then(loadMyUsers)}
However I get the following error:
Fetch API cannot load https://blablabla.heroku.com/users.
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:8080' is therefore not allowed
access. If an opaque response serves your needs, set the request's mode
to 'no-cors' to fetch the resource with CORS disabled.
I tried changing my Fetch method to many things similar to:
const sendSearch = fetch('https://blablabla.heroku.com/users',{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'mode': 'no-cors'
}
})
but the problem persists.
How do I make the cross domain request?
On your heroku server you should add Access-Control-Allow-Origin: * to your response headers, or more specific Access-Control-Allow-Origin: http://localhost:8080 if you wish.
On your production server though, you probably won't need this header, unless you have very good reason for cross origin requests.

Resources