从角度服务调用节点api时发生cors问题

时间:2019-11-05 04:00:22

标签: node.js cors angular7

我有一个Angular7前端,并且试图从我的Node服务器发送一个get请求。但是,节点服务器本身无法接收api请求。

我在节点的app.js代码上都尝试过: 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();
 })

2 个答案:

答案 0 :(得分:1)

您也可以尝试

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

答案 1 :(得分:0)

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