Reputation: 39
I have an Angular7 frontend, and I am trying to send a get request from my Node server. However the Node server is unable to receive the api request itself.
I tried both on node's app.js code: 1>
const cors = require('cors');
app.use(cors());
2>
app.use((req,res,next)=>{
res.header('Access-Control-Allow-Origin', 'http://localhost:4200');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With,
Content-Type, Accept');
next();
})
Upvotes: 0
Views: 623
Reputation: 7822
// Enable CORS
app.use((req, res, next) => {
// This is how you would enable for ALL incoming requests - I don't recommend
// res.header("Access-Control-Allow-Origin", "*");
// Allow multiple [specific] origins - Do it like this
const allowedOrigins = ["https://my-production-app.com", "http://localhost:4200"];
const origin = req.headers.origin;
if (allowedOrigins.indexOf(origin) > -1) {
res.setHeader("Access-Control-Allow-Origin", origin);
}
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
Upvotes: 0
Reputation: 122
You can also try this
let cors = require("cors");
app.use(cors(), function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:4200"); // update to match the domain you will make the request from
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
Upvotes: 1