Node.js 即使在Express和Express gateway上启用CORS,仍受CORS策略的限制

Node.js 即使在Express和Express gateway上启用CORS,仍受CORS策略的限制,node.js,reactjs,cors,microservices,express-gateway,Node.js,Reactjs,Cors,Microservices,Express Gateway,我正在使用expressgateway代理我的微服务。我正在用Axios从我的react应用程序点击网关。但是,调用受到CORS策略的限制。我已经在express gateway和身份验证服务中启用了CORS。我按照官方文档从这个for Express Gateway和这个for authentication service(Express App)启用CORS。下面是我的代码 Express Gateway config.yml policies: - log - proxy -

我正在使用
expressgateway
代理我的微服务。我正在用
Axios
从我的
react
应用程序点击网关。但是,调用受到
CORS策略的限制。我已经在express gateway和身份验证服务中启用了CORS。我按照官方文档从这个for Express Gateway和这个for authentication service(Express App)启用CORS。下面是我的代码

Express Gateway config.yml

policies:
  - log
  - proxy
  - jwt
  - rate-limit
  - request-transformer
  - cors

pipelines:
  authPipeline: 
    apiEndpoints: 
      - auth
    policies: 
      -
        cors:
          -
            action:
              origin: '*'
              methods: 'HEAD,PUT,PATCH,POST,DELETE'
              allowedHeaders: ['Content-Type', 'Authorization']
      - 
        log: 
          action:
            message: 'auth ${req.method}'
      - 
        proxy:
          action: 
            serviceEndpoint: di
身份验证服务app.js

const cors = require('cors');
// Enabling CORS
const corsOptions = {
  origin: '*',
  methods: ['POST', 'GET', 'PATCH', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}
app.use(cors(corsOptions));
当我尝试使用失眠症(像Postman这样的客户端)时,从服务器返回的头可以在下图中看到

我在浏览器控制台中收到此错误

Access to XMLHttpRequest at 'http://127.0.0.1:8080/api/v1/users/login' from 
origin 'http://localhost:3000' has been blocked by CORS policy: Response to 
preflight request doesnt pass access control check: No 'Access-Control- 
Allow-Origin' header is present on the requested resource.
我不确定我错过了什么。如果您还需要什么,请告诉我,我会很快提供。我非常感激每一次试图解释我的案子到底出了什么问题的尝试

编辑:添加API调用片段

const config = {
    headers: {
      'Content-Type': 'application/json',
    },
  };
const body = JSON.stringify({ email, password });
const res = await axios.post('http://127.0.0.1:8080/api/v1/users/login', body, config);
您的“方法”定义不正确。它需要采用YAML数组的形式:

methods: [ "HEAD", "PUT", "PATCH", "POST", "DELETE" ]

尽管您可能希望将“origin”添加到AllowedHeader列表中,但其他一切看起来都正常

更新 我已经使用这个mini-express服务器对此做了一些进一步的测试,然后在Docker上运行API网关和服务器(在gateway.config.yml中进行适当的主机名更改),通过本地主机和浏览器的curl进行测试,一切都如我所期望的那样工作

var express = require('express')
var app = express()

// Enabling CORS
const cors = require('cors');
const corsOptions = {
  origin: '*',
  methods: ['POST', 'GET', 'PATCH', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}
app.use(cors(corsOptions));

function addPath(path) {
  app.use(path, function(req, res, next) {
    const response = `Hello from ${req.method} ${path}`;
    console.log(response);
    res.send(response);
  });
}

addPath('/api/v1/users/*');
addPath('/api/v1/*');

const port = 5000;
app.listen(port, function () {
  console.log(`Example app listening on port ${port}`)
})
我唯一能建议的另一件事是在gateway.config.yml中的cors策略条目之前添加另一条日志消息,如下所示:

- 日志: 行动: 消息:“传入(身份验证):${req.method}${req.path}请求IP:${req.IP}源${req.headers.origin}”

并检查原点的值。如果未定义,请尝试在代理策略之前添加以下响应转换器(当然,将响应转换器添加到可用策略列表中)。我不得不这样做一两次,但我忘记了在什么情况下这是必要的,所以这是一个在黑暗中拍摄

  - response-transformer:
    - condition:
        name: expression
        expression: 'typeof req.headers.origin !== "undefined" && req.headers.origin === "http://localhost"'
      action:
        headers:
          add:
            access-control-allow-origin: '"http://localhost"'

为什么要使用origin:'*'?我只是想让它在不考虑origin的情况下工作。这就是我使用它的原因@但是你难道不知道可能的起源吗?这似乎违背了CORS的目的。你能用一个特定的值试试看它是否有效吗?@JamesMcLeod我只保留了react服务器的端口就试过了。我仍然会得到相同的错误。我会一次又一次地得到相同的错误,即使我将值更改为
origin:'http://localhost:3000/“
方法:[“HEAD”、“PUT”、“PATCH”、“POST”、“DELETE”]
允许的标题:[“Content Type”、“Authorization”]
。我将通过添加如何调用API的片段来更新这个问题。请看一看。所有其他服务器终结点都正常工作吗?这可能是浏览器的问题吗?你试过卷发吗?如果您有任何可以直接从浏览器点击的简单GET API,请尝试从浏览器地址barI尝试用简单的GET从浏览器的地址栏点击网关,它可以工作。但是,当我试图从react中调用相同的端点时,它再次抛出相同的错误。我不确定出了什么问题。其他服务器端点工作正常@PranayNailwal@VenkateshDharavath,从代码片段看,它似乎是在发布而不是获取;如果看不到配置文件的其余部分,我们真的无法对此提供帮助。你能不能用curl,用GET和POST来点击它,看看其中一个/两个都能用?我犯了一个愚蠢的错误,花了很长时间去调试。我只是简单地把
origin:'http://localhost:3000\“
而不是
原点:”http://localhost:3000“
。后面的斜杠就是问题的根源。我接受了这个答案,因为它帮助我调试。谢谢@JamesMcLeod。
var express = require('express')
var app = express()

// Enabling CORS
const cors = require('cors');
const corsOptions = {
  origin: '*',
  methods: ['POST', 'GET', 'PATCH', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization']
}
app.use(cors(corsOptions));

function addPath(path) {
  app.use(path, function(req, res, next) {
    const response = `Hello from ${req.method} ${path}`;
    console.log(response);
    res.send(response);
  });
}

addPath('/api/v1/users/*');
addPath('/api/v1/*');

const port = 5000;
app.listen(port, function () {
  console.log(`Example app listening on port ${port}`)
})
  - response-transformer:
    - condition:
        name: expression
        expression: 'typeof req.headers.origin !== "undefined" && req.headers.origin === "http://localhost"'
      action:
        headers:
          add:
            access-control-allow-origin: '"http://localhost"'