表单提交在控制台中显示奇怪的错误

时间:2019-12-04 14:09:48

标签: javascript node.js angular express mongoose

我正在开发一个小型ToDo应用,其中Angular作为前端,Node.js / Express / Mongo作为中间件/后端。

虽然我在“登录”表单中提交“登录名”,但它命中了登录API,但是它在控制台中返回了一个奇怪的输出,说

  

选项http://localhost:3000/api/v1/users/login/ 0 {}

(请参见下面的屏幕截图),即使成功登录后,我也无法获取仪表板。

我已经通过安装cors NPM模块启用了CORS。并且我已经检查了Postman中的RESTFul服务,并且一切正常。

[更新]这就是我在express.js的{​​{1}}文件中启用CORS的方式。

app.js

Error in console

3 个答案:

答案 0 :(得分:2)

在将CORS请求发送到服务器之前,客户端将始终将此“ OPTIONS”请求作为“预检请求”发送,从而从服务器请求支持的方法。

此请求被阻止可能表明错误的CORS配置或服务器明显阻止了所有“ OPTIONS”请求。 (CORS也需要在服务器上配置。)

可以找到更多信息here

答案 1 :(得分:1)

似乎这是一个known nodejs issue,它仍然打开。

基于开放的github,似乎最好的建议是尝试这样的事情:

  

您需要同时允许:

// Http.OPTIONS method for request that is hitting " apiUrl =https://127.0.0.1:3000/login".
// Allow CORS like below:
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'content-type');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');

另一个好主意是使用角度代理设置进行本地开发,这样您就完全不需要为本地主机添加CORS。

非常好的指导in this SO answer here on setting up a proxy for angular,如果您的工作可行,那么您可以100%确保这确实是CORS问题。

答案 2 :(得分:1)

要处理快递中的CORS,您无需添加任何依赖项。 请注意,http://localhost:4200是您的应用程序。

这对我有用:

//Add here whatever route you are using for the api.
app.use('/api', (req, res, next) => {
  //Where http://localhost:4200 is the angular app
  res.header('Access-Control-Allow-Origin', 'http://localhost:4200'),
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  next();
})

注意: 这将在您导入路线的地方之后以及在使用它们之前。有点像:

const apiRouter = require('./app_api/routes/api_routes');
//The code i posted here
app.use('/api', apiRouter);