如何在 express 上允许特定域的 cors

how to allow cors for specific domain on express

我试图在登录后通过 ajax 从本地主机发送一个 cookie 到其他地方托管的服务器。为了解决与 cookie 相关的错误,我在 axios 中使用:

var instance = axios.create({ 
   withCredentials: true
});

在 expressjs 中我有这个:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

所以,我现在收到这个错误

Failed to load https://foo.herokuapp.com/login: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

我如何告诉 express 将我的域列入白名单,或者我如何发送回 cookie 以便保持登录状态?

要添加更多信息,当我向 expressjs 发出 post(登录)请求时,它 returns 一个 cookie,现在我的浏览器不会自行发送 cookie,所以这是为什么我使用 withCredentials

您将 * 替换为原点(在您的示例中为 http://localhost:8080)。