快递&节点:CORS失败

时间:2017-03-10 04:28:11

标签: node.js express cors

我为Angular 2前端编写了一个Express和Node后端API。

如果在服务器的条目文件中未正确设置CORS,我会收到此常见错误:

  

XMLHttpRequest无法加载https://keilcarpenter-portfolioapi.herokuapp.com/api/sendemail。对预检请求的响应没有通过访问控制检查:否'访问控制 - 允许 - 来源'标头出现在请求的资源上。起源' http://keilcarpenter.co.nz'因此不允许访问。响应的HTTP状态代码为503 ..

以下是来自客户端的http POST请求:

sendEmail(queryObject: any) {
  const body = JSON.stringify(queryObject);
  const headers = new Headers();
  headers.append('Content-Type', 'application/json');
  return this.http.post('https://keilcarpenter-portfolioapi.herokuapp.com/api/sendemail', body, {headers: headers})
  .map((response: Response) => response.json());
}

错误意味着我正在传递预检请求,但它只是一个POST请求,根据我的理解,如果请求只是在此{{3}中确认的GET,POST或HEAD请求之外的任何其他请求,则仅预检}

我很肯定我已根据HTTP Access Control documentation

正确设置了我的CORS标头
// Get dependencies
var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
// Get our API routes
var api = require('./server/routes/api');
var app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
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();
});
// Set our api routes
app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', function (req, res) {
    res.sendFile(path.join(__dirname, 'dist/index.html'));
});
/**
 * Get port from environment and store in Express.
 */
var port = process.env.PORT || '3000';
app.set('port', port);
/**
 * Create HTTP segggrver.
 */
var server = http.createServer(app);
/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, function () { return console.log("API running on localhost:" + port); });
//# sourceMappingURL=server

问题

  • 为什么错误说该请求在POST时会被预检?
  • 为什么我的CORS标题不被接受?

1 个答案:

答案 0 :(得分:2)

由于headers.append('Content-Type', 'application/json')

,请求会获得预检
  

错误意味着我正在传递预检请求,但它只是一个POST请求,根据我的理解,如果请求只是在此{{3}中确认的GET,POST或HEAD请求之外的任何其他请求,则仅预检}

请参阅相同文档的部分内容:

  

如果Content-Type标头的值不是以下值:

     
      
  • application/x-www-form-urlencoded
  •   
  • multipart/form-data
  •   
  • text/plain
  •   

您需要确保您的快速代码以正确的方式处理OPTIONS请求。如需帮助,请参阅HTTP Access Control documentation上的答案或上述评论中的建议,只需使用CORS with Express.js and Angular2,即可为您处理所有这些内容。

相关问题