繁体   English   中英

从 angular 服务调用节点 api 时出现 Cors 问题

[英]Cors issue when making call to node api from angular service

我有一个 Angular7 前端,我正在尝试从我的节点服务器发送一个获取请求。 但是,节点服务器本身无法接收 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();
 })

你也可以试试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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