Sometimes, we may run into the “No ‘Access-Control-Allow-Origin’ header is present on the requested resource” error in our JavaScript app.
In this article, we’ll look at how to fix the “No ‘Access-Control-Allow-Origin’ header is present on the requested resource” error in our JavaScript app.
Fix the “No ‘Access-Control-Allow-Origin’ header is present on the requested resource” Error in a JavaScript App
To fix the “No ‘Access-Control-Allow-Origin’ header is present on the requested resource” error in our JavaScript app, we should enable cross-origin resource sharing (CORS) on the server app.
For instance, if we’re using Express to build our server-side web app, we can use the cors
middleware.
To use it, we write:
const express = require('express')
const cors = require('cors')
const app = express()
const port = 3000
app.use(cors())
app.get('/', (req, res) => {
res.send('hello world')
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
to add the cors
middleware into our Express app with:
app.use(cors())
We installed the cors
package to make it available.
To install it, we run:
npm i cors
Now we should be able to make requests from our JavaScript app to our server-side web app without the No ‘Access-Control-Allow-Origin’ header is present on the requested resource
thrown in our JavaScript browser app.
Conclusion
To fix the “No ‘Access-Control-Allow-Origin’ header is present on the requested resource” error in our JavaScript app, we should enable cross-origin resource sharing (CORS) on the server app.
For instance, if we’re using Express to build our server-side web app, we can use the cors
middleware.