10

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

Miloš Milutinov
  • 375
  • 1
  • 3
  • 16

1 Answers1

10

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.

Florian N.
  • 196
  • 1
  • 8