我想發佈一個json數據,其中包含一組鍵和值從JavaScript到Express.JS。按照其他帖子的建議添加了cors,並且還添加了res.header("Access-Control-Allow-Origin", "*");
。
當我測試Chrome郵遞員應用程序的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發佈請求「原產地不允許」錯誤
我對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);
請隨時提出任何改善。
Hello Lucky Soni,謝謝你的回覆。我嘗試從http:// localhost:8080/webpage.html訪問網頁,服務器返回空白頁面,並顯示錯誤消息「無法GET /webpage.html」。任何想法如何解決這個問題?謝謝 –
確保您在端口8080上運行服務器,並且您有'webpage.html'的路由處理程序(如果您使用類似node.js的服務來提供HTML)。如果您使用的是PHP之類的服務器,請確保在項目文件夾的根目錄中有一個名爲「webpage.html」的文件。 –
非常感謝。問題解決了 :) –