簡體   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