So I have a small angular app which connects to my node api. I don't have a problem with my get request, I get the data from my api on load. My post request throws an error tho;
Access to XMLHttpRequest at 'http://localhost:3000/api/heroes' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
and
ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:3000/api/heroes", ok: false, …}
This is my post method @ client side;
addHero(hero: Hero) {
this.http.post<Hero>("http://localhost:3000/api/heroes", hero)
.subscribe((responseData) => {
console.log(responseData);
})
this.heroes.push(hero); //Adds new hero to original array
this.heroesUpdated.next([...this.heroes]); //Adds new array to subject
}
and here's my backend;
app.use((req,res,next) => {
res.setHeader("Access-Control-Allow-Origin", "localhost");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.setHeader("Access-Control-Allow-Methods","GET, POST, PATCH, DELETE, OPTIONS");
next();
})
app.post("/api/heroes", (req, res,next) => {
const post = req.body;
console.log(post);
res.status(201).json({message:"Succeed"});
});
So I've allowed content-type but I'm still getting the error. Any suggestions how to move on from here?