XMLHttpRequest cannot load Origin http:/localhost:3000 is not allowed by Access-Control-Allow-Origin

XMLHttpRequest cannot load Origin http:/localhost:3000 is not allowed by Access-Control-Allow-Origin

Tech Nursery

1 месяц назад

101 Просмотров

XMLHttpRequest cannot load http://localhost:8081/technursery/user. Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin

This error occurs because of CORS (Cross-Origin Resource Sharing) restrictions. Your front-end running on http://localhost:3000 is trying to access an API hosted on http://localhost:8081, which is considered a different origin, and the server has not allowed this cross-origin request.

To fix the issue, you need to allow cross-origin requests on your backend server.

1. Add the Access-Control-Allow-Origin header on your server: You can add this HTTP header to allow requests from http://localhost:3000. Here’s how:

For a simple solution:

Access-Control-Allow-Origin: http://localhost:3000

Or, for broader access (not recommended for credentialed requests):

Access-Control-Allow-Origin: *


However, don’t use * (wildcard) if your server needs to handle cookies or authentication tokens (withCredentials = true). In such cases, you must specify the exact domain (http://localhost:3000) in the Access-Control-Allow-Origin header.

2. For credentialed requests: If your React front-end is sending requests with withCredentials: true (to send cookies or authentication information), you must specify a specific domain instead of using *:

Access-Control-Allow-Origin: http://localhost:3000


3. Example in Express (Node.js): If you're using an Express server, you can set up CORS like this:


const cors = require('cors');
const app = require('express')();

// Enable CORS with credentials support
app.use(cors({
origin: 'http://localhost:3000',
credentials: true
}));

app.listen(8081, () = {
console.log('Server running on port 8080');
});
Ссылки и html тэги не поддерживаются


Комментарии: