我正在尝试执行以下操作:发送请求。服务器应打印请求正文,然后发送一个小响应。请求的回调应该打印来自服务器的响应。
在某条线上,我做错了什么。我无法弄清楚它是什么。
服务器:
var http = require('http');
var server = http.createServer(function (request, response) {
var reqBody = '';
request.on('data', function (chunk) {
reqBody += chunk;
});
request.on('end', function (chunk) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("<h1>Hello world!</h1>");
console.log(reqBody);
});
});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
请求:
var http = require('http');
var options = {
host: '127.0.0.1',
port: 8000,
path: '/',
method: 'GET',
headers: {"Content-Type": "text/plain"}
};
var reqBody = "<h1>Hello!</h1>";
var req = http.request(options, function(res) {
res.setEncoding('utf8');
var resBody = '';
res.on('data', function (chunk) {
resBody += chunk;
});
res.on('end', function (chunk) {
console.log('response: ' + resBody);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(reqBody);
req.end();
编辑:我得到的错误
problem with request: socket hang up
答案 0 :(得分:2)
问题在于将req.write
与GET
合并,这是无体的。注释你的请求的倒数第二行,它会没事的。