【发布时间】:2019-03-16 17:56:48
【问题描述】:
我是 Node.js 的新手。
我正在尝试向在端口 8080 上本地运行的 Node.js 服务器发出 POST 请求。
但它不起作用。
FireFox 阻止我的 POST 请求,因为它是跨域的
Reason: CORS request not HTTP
这是我的代码:
HTML
<html>
<head>
<title>Progetto Start</title>
<script src="..\Controller\Start.js"></script>
</head>
<body>
<input type="button" id="btPostJSON" value="invia JSON" onclick="SendJSON()"/>
</body>
</html>
Start.js:
function SendJSON() {
xhr = new XMLHttpRequest();
var url = "127.0.0.1:8080";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({"email":"tomb@raider.com","name":"LaraCroft"});
xhr.send(data);
}
节点js服务器:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write(req.url);
res.end();
console.log(req.url);
}).listen(8080);
我正在将 url 打印到控制台并作为响应仅查看它是否有效 有人已经解决了我的问题吗?
【问题讨论】:
-
http请求需要有express js或者类似的库。
-
基本上,您正在尝试发出 http 请求,但您的节点 js 中没有与该请求对应的任何内容。
标签: javascript html node.js http post