【问题标题】:Issue with CORS while trying POST request尝试 POST 请求时出现 CORS 问题
【发布时间】:2017-06-08 19:23:45
【问题描述】:

我正在尝试从运行在 4200 端口上的 angularJS 应用程序向运行在不同端口 3000 上的 nodeJS 应用程序发送发布请求,如下所示。

AngularJS 2.0 代码:

addNewItem(body:string) {
    const headers = new Headers();
    headers.append('Content-Type','application/json');
    return this.http.post('http://10.244.1.59:3000/newBinDevice',body,{
      headers: headers
    })
    .map((response : Response) => response.json());
  }

NodeJS 代码

var express = require('express');

    module.exports = function(app){
        var db = require('./dbclient');
        var bodyParser = require('body-parser');
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({extended:true}));
        db.dbconnection(null,null,null,null,'smartbin',null);
        app.post('/newItem', function(req, res, next) { 
            res.header("Access-Control-Allow-Origin", "*");
            //res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
            res.header("Access-Control-Allow-Headers", "Content-Type"); 
            res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            console.log('body request is ' +  req.body + " after stringifying it " + JSON.stringify(req.body) + " array to string " + req.body.toString());
    }

我收到了 CORS 问题,说 " Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404." 我在某处读到除了

之外无法发送数据
application/x-www-form-urlencoded
multipart/form-data
text/plain

当我尝试从 AngularJS 应用程序发送数据作为字符串而不是 JSON 对象时,我在 nodejs 应用程序上得到空数据。

【问题讨论】:

    标签: angularjs node.js cors http-post


    【解决方案1】:

    您需要在 express 应用程序中添加更多中间件来支持CORS

    您可以使用cors 包:

    var cors = require('cors')
    ...
    app.use(cors());
    app.use(bodyParser.json());
    

    这将启用包的默认 CORS 配置。 documentation 中详细列出了配置选项。

    您问题中代码的问题是您在POST 响应中包含了CORS 标头,但它们需要在飞行前OPTIONS 响应中返回。我建议您使用上面提到的包,而不是编写自己的 CORS 实现。

    【讨论】:

    • 更新了答案
    • 我在上面的代码中做了如下的小改动。 var cors = require('cors'); var coptions = { "origin": "*", "methods": "GET,HEAD,PUT,POST,OPTIONS", "preflightContinue": true }; app.post('/newBinDevice', cors(coptions), function(req, res, next) {console.log(JSON.stringify(req.body));} 虽然服务器正在获取 post 请求,但 post 参数值作为空 json 对象接收。无法弄清楚这里有什么问题。
    • 不要使用preflightContinue。浏览器将发送两个请求:第一个使用OPTIONS 方法;第二个使用POST 方法。 OPTIONS 请求是飞行前请求;您不想在 post 路线中处理它。让cors 模块处理OPTIONS 请求/响应。您看不到正文,因为它没有在 OPTIONS 请求中传递。
    • 我完全删除了 preFlightContinue 并测试了将其设置为 false。在这两种情况下,我仍然收到空的 JSON 对象。当我在浏览器上查看请求负载时,我能够在请求负载中看到 JSON 对象。但在服务器端我收到空对象。
    • 如果请求到达您的post 路由,CORS 问题就解决了。身体是否按您的预期到达与 CORS 无关。使用 CORS,请求被允许或不允许。您的 CORS 问题已解决,我认为与其更新/扩展您的问题来解决您的身体问题,不如提出一个新的与身体相关的问题。
    【解决方案2】:

    我是 stackoverflow 的新手,但之前遇到过这个问题:

    在您的应用中使用此代码。

    var cors = require('cors');
    
    
    app.use(cors({
        'allowedHeaders': ['sessionId', 'Content-Type'],
        'exposedHeaders': ['sessionId'],
        'origin': '*',
        'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
        'preflightContinue': false
    
    }));
    

    并确保在浏览器中禁用 CORS 扩展(如果有)。

    【讨论】:

      猜你喜欢
      • 2021-04-22
      • 2022-11-17
      • 2016-05-18
      • 2020-12-02
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多