简体   繁体   English

CORS 预检请求错误 ExpressJS 和 Angular

[英]CORS preflight request error ExpressJS and Angular

I am trying to create a simple login using an ExpressJS backend, just to test to see how this would work.我正在尝试使用 ExpressJS 后端创建一个简单的登录,只是为了测试它是如何工作的。 But for some weird reason an OPTIONS call is done on to my Angular front-end and throws a CORS error.但是由于一些奇怪的原因,对我的 Angular 前端进行了 OPTIONS 调用,并引发了 CORS 错误。

网络错误

The request headers of the OPTIONS call can be seen in the image below. OPTIONS 调用的请求标头如下图所示。

OPTIONS 调用的请求标头

控制台输出

My ExpressJS Cors setup:我的 ExpressJS Cors 设置:

// There are 2 front-end applications, only the second is used now but it needs to work with both.
env.redirectURL = ['http://localhost:4200', 'http://localhost:5200'];

const app = express();
app.use(cors({ credentials: true, origin: env.redirectURL }));

In this code below I create a JWT token and send it to the front-end using redirection.在下面的代码中,我创建了一个 JWT 令牌并使用重定向将其发送到前端。 This then for some reason calls an "options" request on my front-end which fails.然后由于某种原因,这在我的前端调用了一个“选项”请求,但失败了。

export default (req: Request, res: Response) => {
  if (!req.user) {
    if (env.logging) console.error('No user found!');
    res.status(500).send();
    return;
  }

  const expiresIn = 30 * 60 * 24 * 60000;

  jwt.sign(req.user, env.jwt.secret, { expiresIn }, (err, token) => {
    if (err) {
      if (env.logging) console.error(err);
      res.sendStatus(500); // Handle Error Better
    } else {
      res.cookie('token', token, {
        sameSite: false,
        httpOnly: true,
        secure: env.jwt.secure,
        expires: new Date(new Date().getTime() + expiresIn),
      });

      res.redirect(env.redirectURL[1]);
    }
  });
};

I have been stuck on this for multiple days now and tried to do the same thing months ago as well.我已经坚持了好几天了,几个月前我也试图做同样的事情。 I feel stupid for not being capable of figuring this out and this is my last resort.我因为无法弄清楚这一点而感到愚蠢,这是我最后的手段。

It is very hard to fix this issue without debug.没有调试很难解决这个问题。

Could you try to replace this code?您可以尝试替换此代码吗?

// There are 2 front-end applications, only the second is used now but it needs to work with both.
env.redirectURL = ['http://localhost:4200', 'http://localhost:5200'];

const app = express();
app.use(cors({ credentials: true, origin: env.redirectURL }));

by经过

const allowedOrigins = ['http://localhost:4200', 'http://localhost:5200'];
app.use(cors({
    origin: function (origin, callback) {
        if (!origin) return callback(null, true);
        if (allowedOrigins.indexOf(origin) === -1) {
            const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
            return callback(new Error(msg), false);
        }
        return callback(null, true);
    },
    credentials: true,
}));

暂无
暂无

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

相关问题 Angular $ http.delete CORS错误(预检请求) - Angular $http.delete CORS error (preflight request) CORS angular 应用程序上的预检请求错误部署在 heroku 上,带有节点快递后端 - CORS preflight request error on angular app deployed on heroku with node express backend CORS预检通道未成功…尽管其他请求正常运行,但是一个请求出现此错误 - CORS preflight channel did not succeed…Although other request are working properly but one request is having this cors error Angular POST 请求被 CORS 策略阻止:对预检请求的响应未通过访问控制检查 - Angular POST request been blocked by CORS policy: Response to preflight request doesn't pass access control check CORS 问题 - Angular 8 - NodeJS 和 ExpressJS - CORS Issue - Angular 8 - NodeJS & ExpressJS CORS 仅放置请求的预检问题 - CORS preflight issue on only put request 本地主机上具有Angular的NodeJS + Express:被CORS预检阻止 - NodeJS + Express with Angular on Localhost: Blocked by CORS preflight CORS:飞行前通过,主要请求完成w / 200,但浏览器仍然存在Origin错误 - CORS: preflight passes, main request completes w/200, but browser still has Origin error CORS 错误:对预检请求的响应未通过访问控制检查:它没有 HTTP 正常状态 - CORS Error : Response to preflight request doesn't pass access control check: It does not have HTTP ok status CORS 错误:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段授权 - CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM