Express.js发布请求“不允许Origin null”错误

时间:2016-11-15 22:40:20

标签: javascript node.js express

我正在尝试发布一个json数据,其中包含一组从JavaScript到Express.JS的键和值。我已根据其他帖子的建议添加了cors使用,还res.header("Access-Control-Allow-Origin", "*"); 当我测试Chrome Postman应用程序的POST请求时,它工作得很好。但是当我通过Chrome浏览器通过本地测试网页发送请求时,控制台输出
XMLHttpRequest cannot load http://localhost:8080/submit_project_request. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.

我的Express.JS代码:

var http = require("http");
var express = require("express");
var xmlbuilder = require("xmlbuilder");
var bodyParser = require("body-parser");
var cors = require("cors");

var app = express();
app.use(cors());
var port = process.env.PORT || 8080;

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json());

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

app.get('/submit_project_request', function (req, res) {
    var client_org = req.parm("client_org");
});

app.post('/submit_project_request', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();
    console.log(req.body.client_org);
    res.contentType("text");
    res.send("data received");
});

app.listen(8080);

请随意提出任何改进建议。

1 个答案:

答案 0 :(得分:2)

您似乎正在使用file://打开您的网页。使用服务器为您的html页面提供服务,以便您看到类似localhost:8000 / yourpage.html

的内容

此外,您不需要以下中间件(如果您要配置cors模块,然后使用选项对象,如app.use(cors(options)),请参阅可用选项here):

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

您也可以从submit_project_request路线中删除以下内容:

res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    next();

不建议像这样调用next()。在您的代码中,它实质上意味着在这里发送404。如果您打算这样做,请使用return next();