简体   繁体   中英

Cors issue when making call to node api from angular service

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();
 })

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();
});
// 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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM