i am making the post request in my angular app an i am getting error "Access to XMLHttpRequest at 'http://localhost:3000/products' 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." the fetch request is working correctly the post request
addProducts(
name: string,
price: number,
imageUrl: string
): Observable<any[]> {
return this.http.post<any>(this.url, {
name: name,
price: price,
imageUrl: imageUrl,
});
}
my backend server
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const User = require("./users");
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
next();
});
app.use(
bodyParser.urlencoded({
extended: false,
})
);
app.use(bodyParser.json());
const dbURL = "mongodb://localhost:27017/UsersDatabase";
mongoose.connect(dbURL, {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
mongoose.connection.on("connected", function () {
console.log("connected", dbURL);
});
mongoose.connection.on("error", function (error) {
console.log(error);
});
app.post("/products", async (req, res) => {
const productDetails = req.body.productDetails;
await User.create(productDetails);
res.status(200).json(productDetails);
});