Home > Enterprise >  Access to XMLHttpRequest has blocked by cors Policy:Response to preflight request doesn't pass
Access to XMLHttpRequest has blocked by cors Policy:Response to preflight request doesn't pass

Time:05-16

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

CodePudding user response:

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();
});
  • Related