Javascript Fetch CORS header ‘Access-Control-Allow-Origin’ missing - javascript

When running the following fetch request in my React project:
const options = { method: "GET", headers: { accept: "application/json", "Access-Control-Allow-Origin": "*" } };
response = await fetch(
`https://api.b365api.com/v1/bet365/upcoming?league_id=${league}&sport_id=${sport.id}&token=TOKEN`,
options
).catch((err) => console.error(err));
The request returns with the error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.b365api.com/v1/bet365/upcoming?league_id=131095496&sport_id=1&token=TOKEN. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.
I've searched through A LOT of different pages and haven't found an answer I can use other than using a proxy of some sort like https://cors-anywhere.herokuapp.com/ which has a limit and just doesn't work in production.

Does this or this helps you?
In my experience, there are somethings that can cause CORS errors:
For me, the most common issue is a backend function error... this happens a lot when I'm coding a new feature and happens an unhandled exception in my code. This throws CORS error.
Or maybe you have to config your backend server to use CORS:
import express from 'express'
import cors from 'cors'
const app = express()
app.use( cors() ) // - here
Hope I had helped you, good luck

Related

CORS in Nextjs Application on Vercel

I am currently working wiht my first bigger NextJS application and I ran into the classic CORS problem.
I have a backend, which is hosted on a different server/url, I get my json data from this backend.
My frontend written in NextJS is deployed on Vercel.
I do know, that I have to enable CORS both on the backend side, as well as on the frontend side, in my localhost dev, everything is working fine (even fetching data from backend)
I already followed this guide: https://vercel.com/knowledge/how-to-enable-cors, to enable CORS in my NextJS Application. I modified the nextjs config:
module.exports = {
async headers() {
return [
{
source: "/.*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
}
};
However, when deploying the app on vercel, I receive the following error:
Access to fetch at 'https://<my-censored-backend-url>' from origin 'https://<my-frontend-url>.vercel.app' 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.
In my backend (written in rails), I already configured my frontend on vercel to be allowed for CORS.
Is there anything I am missing?
Do you guys have any experience in CORS and fetching data for NextJS from a different server?
I am using getStaticProps, getServerSideProps AND SWR for fetching.
Any help would be appreciated
I think NextJS has a weird issue that sometimes it just throws the CORS error randomly.
In my case, with a wrong URL it will throw this CORS error.
For example, I used "https://localhost:3000" and then it throws the CORS error. And it worked with "http://localhost:3000".
So my suggestion would be to double check the URL that you are using.
Also, be sure to not include a trailing slash like "http://localhost:3000/" may not work.

CORS Header: Where to put it? And what URL to put?

I have a website that fetches some JSON data from a heroku server I set up. I'm getting a CORS error and I'm not sure how to resolve it.
I am requesting it from a url, let's say, https://www.example.com/content/?id=12345
In my heroku endpoint, I have code that looks like this:
res.set("Access-Control-Allow-Origin", ["https://www.example.com"]);
But I still get this error that says the origins don't match:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at
https://mysterious-hamlet-72124.herokuapp.com/5iucwuFiaK1nJqWwfSHt.
(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://example.com’).
Right now, I just set it to:
res.set("Access-Control-Allow-Origin", ["*"]);
and it works, but I'd like to know how to do it right.
Edit: Thanks for catching my typo...Dang do I feel stupid. I forgot to add "www" on my server-side, like the comments below said.
can you try below code in server side and it will resolve cors issue
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'example.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
app.configure(function() {
app.use(allowCrossDomain);
});
You can use the cors npm package
and add this code to your app.js (or whatever is your main file)
const cors = require("cors");
...
app.use(
cors({
origin: "Your front-end domain",
})
);
this works for me.
But if you want to know more about what CORS is I suggest you Mozilla developer guide

React CORS policy issue with an Axios API in localhost. How can I resolve it?

I'm using an Axios module in my React app, and I am using to API POST method.
Like this:
axios.request({
method: "POST",
url,
responseType: "jsonp",
data: payload,
...config
});
But I get an error:
Access to XMLHttpRequest at 'http://0.0.0.0/api/ak' 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.
xhr.js:160 POST http://0.0.0.0/api/ak net::ERR_FAILED
Where am I wrong?
Setup package CORS in your Express server
https://www.npmjs.com/package/cors

Access Control Origin Header error using Axios

I'm making an API call using Axios in a React Web app. However, I'm getting this error in Chrome:
XMLHttpRequest cannot load
https://example.restdb.io/rest/mock-data. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8080' is therefore not allowed
access.
{
axios
.get("https://example.restdb.io/rest/mock-data", {
headers: {
"x-apikey": "API_KEY",
},
responseType: "json",
})
.then((response) => {
this.setState({ tableData: response.data });
});
}
I have also read several answers on Stack Overflow about the same issue, titled Access-Control-Allow-Origin but still couldn't figure out how to solve this. I don't want to use an extension in Chrome or use a temporary hack to solve this. Please suggest the standard way of solving the above issue.
After trying out few answers I have tried with this,
headers: {
'x-apikey': '59a7ad19f5a9fa0808f11931',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
},
Now I get the error as,
Request header field Access-Control-Allow-Origin is not
allowed by Access-Control-Allow-Headers in preflight response
I'll have a go at this complicated subject.
What is origin?
The origin itself is the name of a host (scheme, hostname, and port) i.g. https://www.google.com or could be a locally opened file file:// etc.. It is where something (i.g. a web page) originated from. When you open your web browser and go to https://www.google.com, the origin of the web page that is displayed to you is https://www.google.com. You can see this in Chrome Dev Tools under Security:
The same applies for if you open a local HTML file via your file explorer (which is not served via a server):
What has this got to do with CORS issues?
When you open your browser and go to https://website.example, that website will have the origin of https://website.example. This website will most likely only fetch images, icons, js files and do API calls towards https://website.example, basically it is calling the same server as it was served from. It is doing calls to the same origin.
If you open your web browser and open a local HTML file and in that HTML file there is JavaScript which wants to do a request to Google for example, you get the following error:
The same-origin policy tells the browser to block cross-origin requests. In this instance origin null is trying to do a request to https://www.google.com (a cross-origin request). The browser will not allow this because of the CORS Policy which is set and that policy is that cross-origin requests is not allowed.
Same applies for if my page was served from a server on localhost:
Localhost server example
If we host our own localhost API server running on localhost:3000 with the following code:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/hello', function (req, res) {
// res.header("Access-Control-Allow-Origin", "*");
res.send('Hello World');
})
app.listen(3000, () => {
console.log('alive');
})
And open a HTML file (that does a request to the localhost:3000 server) directory from the file explorer the following error will happen:
Since the web page was not served from the localhost server on localhost:3000 and via the file explorer the origin is not the same as the server API origin, hence a cross-origin request is being attempted. The browser is stopping this attempt due to CORS Policy.
But if we uncomment the commented line:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/hello', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.send('Hello World');
})
app.listen(3000, () => {
console.log('alive');
})
And now try again:
It works, because the server which sends the HTTP response included now a header stating that it is OK for cross-origin requests to happen to the server, this means the browser will let it happen, hence no error.
Just to be clear, CORS policies are security features of modern day browsers, to protect people from harmful and malicious code.
How to fix things (One of the following)
Serve the page from the same origin as where the requests you are making reside (same host).
Allow the server to receive cross-origin requests by explicitly stating it in the response headers.
If using a reverse proxy such as Nginx, configure Nginx to send response headers that allow CORS.
Don't use a browser. Use cURL for example, it doesn't care about CORS Policies like browsers do and will get you what you want.
Example flow
Following is taken from: Cross-Origin Resource Sharing (CORS)
Remember, the same-origin policy tells the browser to block
cross-origin requests. When you want to get a public resource from a
different origin, the resource-providing server needs to tell the
browser "This origin where the request is coming from can access my
resource". The browser remembers that and allows cross-origin resource
sharing.
Step 1: client (browser) request When the browser is making a cross-origin request, the browser adds an Origin header with the
current origin (scheme, host, and port).
Step 2: server response On the server side, when a server sees this header, and wants to allow access, it needs to add an
Access-Control-Allow-Origin header to the response specifying the
requesting origin (or * to allow any origin.)
Step 3: browser receives response When the browser sees this response with an appropriate Access-Control-Allow-Origin header, the
browser allows the response data to be shared with the client site.
More links
Here is another good answer, more detailed as to what is happening: https://stackoverflow.com/a/10636765/1137669
If your backend support CORS, you probably need to add to your request this header:
headers: {"Access-Control-Allow-Origin": "*"}
[Update] Access-Control-Allow-Origin is a response header - so in order to enable CORS - you need to add this header to the response from your server.
But for the most cases better solution would be configuring the reverse proxy, so that your server would be able to redirect requests from the frontend to backend, without enabling CORS.
You can find documentation about CORS mechanism here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
I had a similar problem and I found that in my case the withCredentials: true in the request was activating the CORS check while issuing the same in the header would avoid the check:
Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’
Do not use
withCredentials: true
but set
'Access-Control-Allow-Credentials':true
in the headers.
For Spring Boot - React js apps I added #CrossOrigin annotation on the controller and it works:
#CrossOrigin(origins = {"http://localhost:3000"})
#RestController
#RequestMapping("/api")
But take care to add localhost correct => 'http://localhost:3000', not with '/' at the end => 'http://localhost:3000/', this was my problem.
I had the same error. I solved it by installing CORS in my backend using npm i cors. You'll then need to add this to your code:
const cors = require('cors');
app.use(cors());
This fixed it for me; now I can post my forms using AJAX and without needing to add any customized headers.
For any one who used cors package change
const cors = require('cors');
app.use(cors());
to
const cors = require('cors');
app.use(cors({credentials: true, origin: 'http://localhost:5003'}));
change http://localhost:5003 to your client domain
Using the Access-Control-Allow-Origin header to the request won't help you in that case while this header can only be used on the response...
To make it work you should probably add this header to your response.You can also try to add the header crossorigin:true to your request.
First of all, CORS is definitely a server-side problem and not client-side but I was more than sure that server code was correct in my case since other apps were working using the same server on different domains. The solution for this described in more details in other answers.
My problem started when I started using axios with my custom instance. In my case, it was a very specific problem when we use a baseURL in axios instance and then try to make GET or POST calls from anywhere, axios adds a slash / between baseURL and request URL. This makes sense too, but it was the hidden problem. My Laravel server was redirecting to remove the trailing slash which was causing this problem.
In general, the pre-flight OPTIONS request doesn't like redirects. If your server is redirecting with 301 status code, it might be cached at different levels. So, definitely check for that and avoid it.
After a long time of trying to figure out how CORS works. I tried many way to fix it in my FE and BE code. Some ways CORS errors appearance, some ways the server didn't receive body from client, and other errors...
And finally got this way. I'm hoping this can help someone:
BE code (NodeJS + Express)
var express = require("express");
const cors = require("cors");
var app = express();
app.use(
cors({
origin: "*",
})
);
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
// your routers and codes
My FE code (JS):
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Connection: 'Keep-Alive',
Authorization: `Bearer test`,
},
body: JSON.stringify(data),
});
I imagine everyone knows what cors is and what it is for.
In a simple way and for example if you use nodejs and express for the management, enable it is like this
Dependency:
https://www.npmjs.com/package/cors
app.use (
cors ({
origin: "*",
... more
})
);
And for the problem of browser requests locally, it is only to install this extension of google chrome.
Name: Allow CORS: Access-Control-Allow-Origin
https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=es
This allows you to enable and disable cros in local, and problem solved.
npm i cors
const app = require('express')()
app.use(cors())
Above code worked for me.
You can create a new instance of axios with a custom config, and then use this new configured instance,
create a file with axios-configure.js, add this sharable exported method and use this preconfigured import, rather importing axios directly like we use traditionally,
import axios from 'axios';
import baseUrl from './data-service';
const app = axios.create({
baseURL: baseUrl,
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
},
withCredentials: true
})
export default app;
use this exported function like,
import axios from '../YOUR_DIRECTORY/axios-configure';
axios.get();// wont throw cors
dont import axios from axios;
then use axios.get() it will dont throw cors worked for us,
NOTE this solution will work for them who facing CORS at local environment as local starts at 5000 and backend at 8080, but in production, build gets deployed from java 8080 no CORS in productions (Facing CORS at only local environment)
As I understand the problem is that request is sent from localhost:3000 to localhost:8080 and browser rejects such requests as CORS. So solution was to create proxy
My solution was :
import proxy from 'http-proxy-middleware'
app.use('/api/**', proxy({ target: "http://localhost:8080" }));
$ npm install cors
After installing cors from npm add the code below to your node app file. It solved my problem.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
I had a similar problem when I tried to create the React Axios instance.
I resolved it using the below approach.
const instance = axios.create({
baseURL: "https://jsonplaceholder.typicode.com/",
withCredentials: false,
headers: {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
}
});
try it proxy
package.json add code:
"proxy":"https://localhost:port"
and restart npm enjoy
same code
const instance = axios.create({
baseURL: "/api/list",
});
You can use cors proxy in some specific cases - https://cors.sh
In node js(backend), Use cors npm module
$ npm install cors
Then add these lines to support Access-Control-Allow-Origin,
const express = require('express')
const app = express()
app.use(cors())
app.get('/products/:id', cors(), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for a Single Route'});
});
You can achieve the same, without requiring any external module
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
},
"proxy": "http://localhost:8080",
"devDependencies": {
use proxy in package.json

CORS preflight request error not solved by installing npm cors package

After getting below console error (from use of fetch api),
Console Error:
Fetch API cannot load https://... Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'https://...' is
therefore not allowed access. The response had HTTP status code 404.
If an opaque response serves your needs, set the request's mode to
'no-cors' to fetch the resource with CORS disabled.
I attempted solve the issue by installing the npm cors package.
npm install cors --save
Then added to server.js
const cors = require('cors');
app.use(cors());
Cors package setup instructions:
https://www.npmjs.com/package/cors
But I'm still getting the same preflight request error. Can anyone advise if additional setup for cors package is required, or if something else might need to be done?
Probably the server is not adding "Access-Control-Allow-Origin" or the header value has wrong domain. Try sending "Access-Control-Allow-Origin" header with value * and see if it works.
You can see more here https://dariuscoder.com/2021/09/16/how-to-debug-cors/
Since you say it is 404 code, so maybe your application/framework you use does not add the header in case it did not find some resource.

Categories

Resources