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
Hello, this is my request:
axios({ method: 'POST', url:${SERVER_ADDRESS}/api/v1/manager/restaurant/${restaurantName}/payment-methods, crossDomain: true, data: { payment_methods: checkedPayments }, }) .then(() => { dispatch(loadPayments(restaurantName)); }).catch((error) => { console.log(error); dispatch(paymentsError()); });
the server is laravel 5, it is responding with:
XMLHttpRequest cannot load http://localhost:8000/api/v1/manager/restaurant/accusamus/payment-methods. 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.
Server headers are set with CORS middleware like this:
return $next($request)
->header("Access-Control-Expose-Headers", "Access-Control-*")
->header("Access-Control-Allow-Headers", "Access-Control-*, Origin, X-Requested-With, Content-Type, Accept")
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD')
->header('Access-Control-Allow-Origin', '*')
->header('Allow', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
Theese are the response headers, which I get when I use postman:
Access-Control-Allow-Headers →Access-Control-, Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Allow-Origin →
Access-Control-Expose-Headers →Access-Control-*
Allow →GET, POST, PUT, DELETE, OPTIONS, HEAD
Cache-Control →no-cache
Connection →close
Content-Type →text/html; charset=UTF-8
Date →Sat, 03 Dec 2016 10:33:04 GMT
Host →localhost:8000
X-Powered-By →PHP/7.0.13
X-RateLimit-Limit →60
X-RateLimit-Remaining →59
phpdebugbar-id →0ff14bef1824f587d8f278c87ab52544
AXIOS sends preflight which is:
Request URL:http://localhost:8000/api/v1/manager/restaurant/accusamus/payment-methods
Request Method:OPTIONS
Status Code:200 OK
Remote Address:[::1]:8000
Response Headers
view source
Allow:GET,HEAD,POST
Cache-Control:no-cache
Connection:close
Content-Type:text/html; charset=UTF-8
Date:Sat, 03 Dec 2016 10:25:27 GMT
Host:localhost:8000
X-Powered-By:PHP/7.0.13
Request Headers
view source
Accept:/
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:8000
Origin:http://localhost:3000
Referer:http://localhost:3000/restaurant-profile/payment
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36
Am I doing something wrong? I can’t figure it how to do this. Witch Chrome plugin CORS everything works fine, but this is not the way.
Please help, help is really appreciated, spent hours with this.
I’m using axios to make a axios.get call in my redux action.js file.
In my component this action is performed on form submission.
I’m getting status 200 in my console but not getting any response back.
I’m getting the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:\\localhost:3000' is therefore not allowed access.
Has anybody came across such error too? Would you please share on how to resolve this.
asked Feb 2, 2016 at 21:28
3
The problem is not with axios. The issue is with the server. When you serve up data you must add the following headers, before sending it.
Access-Control-Allow-Origin
must be set to
*
Access-Control-Allow-Headers
must be set to
Origin, X-Requested-With, Content-Type, Accept
answered Jun 17, 2016 at 20:21
3
The first confusion I had tackling this problem was understanding what a preflight request means. So I will start from there.
Browsers send preflight requests whenever a request does not meet these criteria:
- HTTP methods matches one of (case-sensitive):
- GET
- POST
- HEAD
- HTTP Headers matches (case-insensitive):
- Accept
- Accept Language
- Content Language
- Last-Event-ID
- Content-Type, but only if the value is one of:
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
Preflight requests are made with an OPTIONS method that includes three additional headers that your server may not be expecting if it is not configured for CORS. They are:
- Access-Control-Allow-Headers
- Access-Control-Allow-Origin
- Access-Control-Allow-Methods
If the server isn’t configured for CORS, it simply responds with an empty header having HTTP status code 200. Once you have configured the server for CORS, you should include the headers listed above as headers supported by CORS.
That should clear the error and allow you communicate with the server.
Note: While your server can handle the custom header you created (in my case, Authorization for JWT authentication), it most likely won’t be configured for CORS request. If you have access to your server, simply find out how to configure CORS for that server.
For more information about CORS. See https://www.html5rocks.com/en/tutorials/cors/
answered Jan 12, 2017 at 6:38
erika_dikeerika_dike
2514 silver badges7 bronze badges
0
Please try this.. it worked for my case { crossdomain: true }.
axios.get(`http://localhost:4000/api`,{ crossdomain: true }).then((result)=>{
console.log("result",result.data.result.[0].name);
}).catch((error)=>{
console.log("Error hey",error);
});
answered Apr 5, 2021 at 11:49
This worked for me:
axios.create({
baseURL: "http://localhost:8088"
}).get('/myapp/user/list')
.then(function(response) {
callback && callback(response);
debugger;
})
answered May 8, 2019 at 0:39

Problem :
Making an API call using Axios in a React Web app. However, I’m getting this error:
Axios request has been blocked by cors no 'Access-Control-Allow-Origin' header is present on the requested resource
Solution 1:
Access-Control-Allow-Origin is a response header — so in order to enable CORS — We need to add this header to the response from server.
headers: {"Access-Control-Allow-Origin": "*"}
Solution 2:
For most cases, the better solution would be configuring the reverse proxy, so that server would be able to redirect requests from the frontend to the backend, without enabling CORS.
You can find documentation about CORS mechanism here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Solution 3:
Server should enable the cross origin requests, not the client. To do this, We can check this nice page with implementations and configurations for multiple platforms.
Thank you for reading the article. If you face any problems, please comment below. To learn more about react, you can check The complete React developer course w/Hooks & Redux course.
CORS actually stands for Cross-Origin Resource Sharing and is a mechanism that allows services to communicate with each other. You must have come across the infamous error that bothered almost every single person dabbling with web development. I came across it as well and was utterly frustrated with it.
SOP
Same Origin Policy (SOP) is a mechanism implemented by modern web browsers that block your application from requesting data that lives on a different URL. If you make a request that lives on a different URL or origin, the browser will block this data from being shared in your application. And to make matters worse it will throw these really vague errors that make it almost impossible for newbies to debug.
Client and Server
I have used the demo example of the express server taken from the official documentation. The application is running on port 4000 and we have only one route / that responds with a string ‘Hello World!’
const express = require('express')
const app = express()
const port = 4000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
On the client side, we are using a freshly generated React project that makes a request to our server and logs the output to the console. We’re using axios to help us make that request.
import axios from 'axios'
function App() {
const fetchData = async () => {
const resp = await axios.get('http://localhost:4000')
console.log(resp)
}
fetchData()
return (
<>
</>
);
}
export default App;
But when you check the console of your client application you can see that some things didn’t go exactly as planned.
Does the screenshot below look familiar to you? You most likely came across it when trying to write a React application that interacts with your server
If yes then keep on reading this article as we’ll quickly get rid of it. Let’s start by translating the error into plain English so that we could be on the same page when it comes to understanding why the applied fix works.
Origin, in this case, is defined as a combination of URI, hostname and port in the following format SCHEME://HOSTNAME:PORT. In the example of my application, my client is running on
http://localhost:3000
but my server is running at
http://localhost:4000
Solution
The solution to this problem needs to be implemented on the server. We will make use of the CORS middleware to help us with that. Let’s start by installing it on our server. Run the following command in the root directory of your server application
$ npm install cors
We can now go ahead and use it in our application.
const express = require('express')
const app = express()
const cors = require('cors')
const port = 4000
app.use(cors())
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Now restart the server and refresh your client in the browser, you will see that the error went away and the response is printing in the console as expected.
In our case, we have taken the easy way out and enabled CORS requests across all of the routes in our application. If you’re working on a slightly more complicated project then you should take a look at the official documentation and check for yourself on how to best handle this error.
Hello! I’m Dawid. I’m a full-stack developer with a couple of years of experience under my belt. I spent most of my career working with React. I also built reacterry.com, an online portal with React coding challenges.






