[英]Receiving a node.js response in browser code after a POST of FormData
New to JavaScript. JavaScript 的新功能。 I'm POSTing FormData to a node and attempting to capture a response.
我正在将 FormData 发布到节点并尝试捕获响应。 The POST works fine but I can't seem to capture the response from the node in the browser code.
POST 工作正常,但我似乎无法从浏览器代码中的节点捕获响应。 The contents of res.end(), instead, appear in a new browser page.
res.end() 的内容会出现在新的浏览器页面中。 The code in the xhr.onload function does not get executed.
xhr.onload function 中的代码不会被执行。
Either there's something I don't understand or there's something I'm doing wrong (or both).要么有一些我不明白的地方,要么有一些我做错了(或两者兼而有之)。
Any help is appreciated.任何帮助表示赞赏。
HTML... HTML...
<form id="InstallDB" action="http://127.0.0.1:3000" method="POST">
[blah]
<input type="submit" value=" Install DB ">
</form>
<script>
var formData = new FormData(document.getElementById("InstallDB"));
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://127.0.0.1:3000");
xhr.setRequestHeader("Content-Type", "text/text");
xhr.send(formData);
xhr.onload = function(){
if (xhr.status == 200) {
console.log("GOT HERE");
console.log(xhr.responseText);
}
else {
alert(`Error ${xhr.status}: ${xhr.statusText}`);
}
};
xhr.onerror = function() {
console.log("Network error occurred")
}
</script>
node.js... node.js...
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer(function(req, res) {
if (req.method === "POST") {
var body = "";
req.on("data", function (chunk) {
body += chunk;
});
req.on("end", function(){
console.log("Server received = " + body);
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end(hostname + ", port " + port + ". Successful POST.");
});
}
}).listen(port, hostname);
I resolved this issue by adding headers in the node code.我通过在节点代码中添加标头解决了这个问题。
Changed:改变:
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
to:至:
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": "true" });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.