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.
Error
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.
💬 Leave a comment