我在尝试做与网络服务器等相关的事情方面非常陌生,并且在尝试将数据从网站上运行的 javascript 发送到本地运行的服务器时遇到了困难。我已经能够让它们进行通信,但我在服务器上获得的所有数据始终只是“[object object]”,而不是我从浏览器发送的字符串。
这就是服务器当前的样子,非常简单:
http.createServer(function(request, response){
response.writeHead(200, {"Content-Type": "text/plain"});
console.log("request recieved: " + response + request);
}).listen(8001);
这是我从浏览器发送的内容:
var url = "http://localhost:8001";
$.ajax({
url: url,
type: "POST",
data: "Hello friend",
contentType: "text/plain",
});
我也尝试过类似的方法,但导致了同样的问题:
var http = new XMLHttpRequest();
var sendData = "HELLO";
http.open("POST", "http://localhost:8001", true);
http.setRequestHeader("Content-type", "text/plain");
http.send(sendData);
我还尝试在服务器端使用 JSON.stringify 来尝试获取字符串,但这会返回一个错误,指出它不能用于“圆形对象”。
如果这个问题真的很愚蠢,我很抱歉,正如我所说,我是一个完全的初学者,这是我第一次尝试做类似的事情。我尝试过研究如何采取不同的做法,但在尝试了无数选择之后,我觉得我需要在这里提问。
提前致谢!如果需要更多信息,我很乐意尝试扩展该问题!
最佳答案
当您使用连接(+)
运算符时,JavaScript会将对象
转换为字符串
。对象的默认 String
表示形式为 [object object]
。这就是为什么它打印 [object object]
。
http.createServer(function(request, response){
response.writeHead(200, {"Content-Type": "text/plain"});
console.log("request recieved: " , response , request);
}).listen(8001);
如果您想获取正文,则可以监听 data
事件并使用数据。
http
.createServer(function(request, response) {
let body = "";
request.on("data", chunk => {
body += chunk.toString(); // convert Buffer to string
});
request.on("end", () => {
console.log(body);
response.end('ok');
});
})
.listen(8001);
I will recommend to use
express
package to avoid all boilerplate code.
关于javascript - 使用 Node http 发送和接收纯文本而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60017306/