I'm executing a simple delete command to remove one of my toDos in my toDoList react app and I get the response the response that XMLHTTPRequest to my url is blocked by CORS policy and AxiosError returns me a network error
Access to XMLHttpRequest at 'url' from origin http://localhost:3000 has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I have checked yt axios tutorials and they don't have this issue. Some solutions I found online is to make a backend with Access-Control-Allow- Origin response header on my domain which I don't really understand because I am still learning backend.
Any tips on fixing the problem without having to set up a backend or a link to a tutorial on setting pu a backend with my react app would be appreciated.
const deleteHandler = async (id) => {
try {
console.log(id)
await axios.delete(
`{url}.json/${id}`
);
const toDoList = toDos.filter((toDo) => toDo.id !== id);
setToDos(toDoList);
} catch (err) {
console.log(err);
}
};
I tried to find solutions to fix the problem but so far nothing worked and i am really stuck. I found a stackoverflow question to oxforddictionary problem that's the same as mine but i don't know how to apply it to my firebaes database.
I'm trying to get XML data with a fetch() request and the appropriate header.
The request succeeds but the reponse is empty. The weird part is that the browsers networking tab in the debugger gives me a 200 OK and has the requested Response payload but I can't seem to get this data even though it's present. Any clues as to why?
Snapshot of the debugger
data = {
get:(url)=>{
return new Promise(resolve => {
let auth = new Headers({
"username":key.user,
"password":key.password,
"Accept":"application/xml"
})
fetch(url,{
method:"get",
mode:"no-cors",
headers: auth,
credentials:"include"
})
.then(response => console.log(response))
//empty response
})
}
}
You are making a cross-origin request but you said mode:"no-cors",.
mode:"no-cors", means "If I need permission to do something cross-origin, then don't ask for it, and don't throw an error".
no-cors — Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers. If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are simple headers. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.
Since you need permission to read data from a cross-origin request, it is failing silently (because you explicitly told it to do so).
Use mode: "cors".
I've been trying to create a react web app for a few days now for my internship and I've encountered a CORS error. I am using the latest version of reactJS, and placing this in the create-react-app, and below is the code for fetching:
componentDidMount() {
fetch('--------------------------------------------',{
method: "GET",
headers: {
"access-control-allow-origin" : "*",
"Content-type": "application/json; charset=UTF-8"
}})
.then(results => results.json())
.then(info => {
const results = info.data.map(x => {
return {
id: x.id,
slug: x.slug,
name: x.name,
address_1: x.address_1,
address_2: x.address_2,
city: x.city,
state: x.state,
postal_code: x.postal_code,
country_code: x.country_code,
phone_number: x.phone_number,
}
})
this.setState({warehouses: results, lastPage: info.last_page});
})
.then(console.log(this.state.warehouses))
}
I'm sorry that I can't post the url for the API due to company rules, however, it is confirmed that there are no CORS setting in the API backend.
However, I encounter the following errors when run on mozilla
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ------------------. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
and
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ---------------------------------------------. (Reason: CORS request did not succeed).
If run on chrome it gives the following error
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
and
Failed to load --------------------------------------------------------: 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:3000' is therefore not allowed access. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
and
Uncaught (in promise) TypeError: Failed to fetch
Another thing is that I am able to open the url in my browsers with no problems or whatsoever.
Please help and thanks!
Additional Information
The reason I added the CORS setting is because it gives a CORS error, so removing it does not really solve the issue.
Next I tried to perform proxy setting, however, it now gives
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
According to the internet this is caused becasue the response is not a JSON. However when I checked the API it gives this
api img
which means that return type should be a JSON right?
Additional Info
checking the respond will yield this
{"status":200,"total":1,"per_page":3,"current_page":1,"last_page":1,"next_page_url":null,"prev_page_url":null,"from":1,"to":3,"data":[{"id":1,"slug":"america","name":"america","address_1":"USA Court","address_2":"USA","city":"USA","state":"USA","postal_code":"94545","country_code":"US","phone_number":"10000001","created_by":null,"updated_by":null,"created_at":"2017-11-10 11:30:50+00","updated_at":"2018-06-28 07:27:55+00"}]}
The CORS settings need to be setup in the API to allow access from your React app domain. No CORS settings, no AJAX from different domains. It's simple as that. You can either add CORS settings to your company API (this is unlikely to happen) or you can work around like described below:
The CORS is solely a mechanism of client browser to protect users from malicious AJAX. So one way to work around this is proxying your AJAX request from your React app to its own web server. As Vincent suggests, the create-react-app provides an easy way to do this: in your package.json file, simply chuck "proxy": "http://your-company-api-domain". For more details, please see this link
Then in your react app you can using relative URL like this: fetch('/api/endpoints'). Notice that the relative URL has to match with your company API. This will send a request to your server, then the server will forward the request to your company API and return the response back to your app. Since the request is handled in the server-to-server way not browser-to-server so the CORS check won't happen. Therefore, you can get rid of all unnecessary CORS headers in your request.
This is what I did using vite
Package.json file add:
"proxy": "http://api_website_where_the_request_is_comming/",
App component or whatever component you making the call do this
let endpoint = /api/your_endpoint/;
fetch(endpoint).then(function (response) {
return response.json()
})
.then(function (jsonData){
console.log('Banner log', jsonData);
})
In your backend, make sure that the app is use cors.
Run this to install cors
npm install cors --save
Import cors in the app using
const cors = require('cors');
app.use(cors()) // if name of your backend is app
I'm trying to fetch and cache some external resources/websites using a service worker.
My code in service-worker.js is the following:
'use strict';
var static_urls = [
'https://quiqqer.local/test?app=1',
'https://quiqqer.local/calendar?app=1'
];
self.addEventListener('install', function (event)
{
event.waitUntil(
caches.open('ionic-cache').then(function(cache) {
cache.addAll(static_urls.map(function (urlToPrefetch)
{
console.log(urlToPrefetch);
return new Request(urlToPrefetch, {mode: 'no-cors'});
})).catch(function(error) {
console.error(error);
}).then(function() {
console.log('All fetched and cached');
});
})
);
});
Which creates this output:
service-worker.js: https://quiqqer.local/test?app=1
service-worker.js: https://quiqqer.local/calendar?app=1
service-worker.js: TypeError: failed to fetch
service-worker.js: All fetched and cached
(index): service worker installed
What is the reason for the failing fetch?
My site https://quiqqer.local has set the header Access-Control-Allow-Origin to '*'
Maybe it's my self-signed certificate for my site?
I added an exception for this certificate, so if I open the site Chrome shows that the site isn't secure next to the URL bar but the content is still displayed.
Since you're explicitly setting {mode: 'no-cors'}, you're going to get back an opaque Response—one that always has a response code of 0.
cache.add() will throw a TypeError if the Response that you're attempting to add to the cache has a code outside of the 2xx range.
Because you have CORS enabled on your server, via the Access-Control-Allow-Origin header, you can just make a request with its mode set to 'cors'. 'cors' mode is the default for cross-origin URLs, so
cache.addAll(static_urls)
.then(...)
.catch(...);
should give you the behavior that you want.
If you were making a request against a server that didn't support CORS, and you wanted to cache it, then you'd have to explicitly set {mode: 'no-cors'} and use a combination of fetch() + cache.put() to add the opaque response the cache. (And you'd have to assume the risk that the opaque response isn't a 4xx or 5xx error, since there's no way of knowing.) But, you don't have to worry about that because your server does support CORS.
I added CORS extension to chrome. When called ajax from localhost I got response in the form of XML. If I disabled CORS extension I got the following error. I referred so many questions in this community. But I cant't resolve my problem. It may duplicate but I'm asking this question for help with hope.
XMLHttpRequest cannot load https://buzz.machaao.com/feed. 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:3000' is therefore not allowed access. The response had HTTP status code 401..
And my code is
HTTP.get('https://buzz.machaao.com/feed',{
headers: {
"Access-Control-Allow-Origin" : "*"
}
}, (err, res) => {
if(err) {
console.log(err);
}
else {
console.log(res);
}
});
The https://buzz.machaao.com/feed site doesn’t send the Access-Control-Allow-Origin response header, so you need to make your request through a proxy instead—like this:
var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
targetUrl = 'http://catfacts-api.appspot.com/api/facts?number=99'
HTTP.get(proxyUrl + targetUrl,
(err, res) => {
if(err) {
console.log(err);
}
else {
console.log(res);
}
});
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains why browsers won’t let you access the response cross-origin from frontend JavaScript code running in a web app unless the response includes an Access-Control-Allow-Origin response header.
https://buzz.machaao.com/feed has no Access-Control-Allow-Origin response header, so there’s no way your frontend code can access the response cross-origin.
Your browser can get the response fine and you can even see it in browser devtools—but your browser won’t expose it to your code unless it has a Access-Control-Allow-Origin response header. So you must instead use a proxy to get it.
The proxy makes the request to that site, gets the response, adds the Access-Control-Allow-Origin response header and any other CORS headers needed, then passes that back to your requesting code. And that response with the Access-Control-Allow-Origin header added is what the browser sees, so the browser lets your frontend code actually access the response.