Preflight request doesn't pass access control check: It does not have HTTP ok status problem and i don't know why, i imported everything right

Viewed 11927

I'm getting this error where it says "Response to preflight request doesn't pass access control check: It does not have HTTP ok status." Anyone have any idea on what could it be?

This is my code on backend:

app.js

app.delete("api/posts/:id", (req,res,next) =>{
  console.log(req.params.id);
  res.status(200).json({message: 'post deleted!'})
})

This is the code on frontend:

posts.service.ts:

deletePost(postId: string) {
    this.http
      .delete('http://localhost:3000/api/posts/' + postId)
      .subscribe(() => {
        console.log('deleted');
      });
  }

post-list.component.ts

onDelete(postId: string) {
    this.postsService.deletePost(postId);
  }

And post-list.component.html:

<button mat-button color="warn" (click)="onDelete(post.id)">DELETE</button>

Note that I DID ALLOW CORS in my code, here's the proof:

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, PUT, DELETE, OPTIONS"
  );
  next();
});

Here's a picture of the problem: Problem

1 Answers

Preflight requests are not handeled as "normal" request. They have the http OPTIONS header.So after your code snippet where you set the CORS header just add the following lines:

app.options('/*', (_, res) => {
    res.sendStatus(200);
});

This just sets the status to 200 and should fix your problem.

Related