Table of Content
The CORS error "No 'Access-Control-Allow-Origin' header is present on the requested resource" typically occurs when your client-side JavaScript (like in a web browser) tries to make a request to a server that doesn't allow cross-origin requests by default.
To fix this error, you need to configure the server to allow cross-origin requests. Here are steps to resolve the issue depending on the server environment:
1. Server-Side Solution (Setting Headers)
The main fix is to ensure that your server includes the Access-Control-Allow-Origin
header in its response. The solution differs depending on your server-side framework:
Node.js (Express)
You can use the CORS middleware to allow cross-origin requests.
Install the cors
package:
npm install cors
In your app.js or server.js file:
const express = require('express');
const cors = require('cors');
const app = express();
// Allow all origins
app.use(cors());
// Or allow specific origins
app.use(cors({
origin: 'http://example.com'
}));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Apache
If you are using an Apache server, you can enable CORS by modifying the .htaccess
file or the virtual host configuration.
Add the following to your .htaccess
or Apache config file:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
This allows requests from any origin. For a specific origin, replace "*"
with the domain, e.g., "http://example.com"
.
NGINX
In the NGINX configuration file, you can set the CORS headers by adding:
server {
location / {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization';
}
}
2. Frontend Solution (Proxy Requests)
If you don’t have control over the server and can’t set headers, you can use a proxy server to route requests through your own domain.
- For example, using webpack-dev-server:
devServer: {
proxy: {
'/api': {
target: 'http://example.com',
changeOrigin: true,
pathRewrite: { '^/api': '' },
},
},
}
3. Handling Preflight Requests (for OPTIONS
method)
For PUT
, PATCH
, or DELETE
requests, browsers send a preflight request using the OPTIONS
method. Ensure your server handles this by responding with appropriate CORS headers.
4. Allow Credentials (if required)
If you need to allow cookies or authentication headers, add the Access-Control-Allow-Credentials
header:
Access-Control-Allow-Credentials: true
And ensure you specify the exact origin instead of "*"
for Access-Control-Allow-Origin
.
By implementing one of these server-side or proxy solutions, the CORS error should be resolved.
Discussion