CORS飞行前请求错误ExpressJS和Angular

时间:2020-07-06 06:36:34

标签: node.js typescript express cors

我正在尝试使用ExpressJS后端创建一个简单的登录名,只是为了进行测试以查看其工作方式。 但是出于某些奇怪的原因,对我的Angular前端进行了一次OPTIONS调用,并抛出了CORS错误。

Network Error

在下图中可以看到OPTIONS调用的请求标头。

The OPTIONS call's request headers

The console output

我的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 }));

在下面的这段代码中,我创建一个JWT令牌,并使用重定向将其发送到前端。然后由于某种原因,这在我的前端调用了一个“选项”请求,但失败了。

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

我已经坚持了好几天,并在几个月前也尝试做同样的事情。我无能为力,这很愚蠢,这是我的最后选择。

1 个答案:

答案 0 :(得分:-1)

没有调试就很难解决这个问题。

您可以尝试替换此代码吗?

{
  "name": "tailwindcss",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "tailwindcss": "^1.4.6"
  },
  "devDependencies": {},
  "scripts": {
    "build:css": "tailwind build src/style.css -o style.css",
    "live": "live-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

作者

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