Surendra
Surendra

Reputation: 31

Access to XMLHttpRequest has blocked by cors Policy:Response to preflight request doesn't pass access control check

Error:

Access to XMLHttpRequest at 'http://localhost:8000/hirings/hiring' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

headers

app.use((req,res,next)=>{
    res.header('Access-Control-Allow-Headers, *, Access-Control-Allow-Origin', 'Origin, X-Requested-with, Content_Type,Accept,Authorization','http://localhost:4200');
    if(req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods','PUT,POST,PATCH,DELETE,GET');
        return res.status(200).json({});
    }
    next();
});

app.use(cors());

Pleae give the solutions for this problem

Upvotes: 0

Views: 13444

Answers (2)

AditYa
AditYa

Reputation: 897

In my case, I am using a CloudFront distribution for the UI code deployed on S3. From S3, the UI code requests go to the API server, and I encountered the same error in the browser console. It was misleading, indicating CORS issues, but the root cause was CloudFront's inability to connect to the origin server. Therefore, it's essential to check the health and reachability of the origin server to resolve this issue.

Upvotes: 0

Abdurrahim Ahmadov
Abdurrahim Ahmadov

Reputation: 561

The order of middleware is important in the express framework. You can fix it as follows:

app.use(cors());
app.use((req,res,next)=>{
    res.header('Access-Control-Allow-Headers, *, Access-Control-Allow-Origin', 'Origin, X-Requested-with, Content_Type,Accept,Authorization','http://localhost:4200');
    if(req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods','PUT,POST,PATCH,DELETE,GET');
        return res.status(200).json({});
    }
    next();
});

Upvotes: 3

Related Questions