晚上,这里是初学者。
我正在尝试向使用本地请求的服务器发出一个简单的请求,并且希望将响应显示在控制台上,但是我不知道应该使用响应的哪个属性来访问它
这是服务器:
const {createServer} = require("http");
let server = createServer((request, response) => {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(`
<h1>Hello!</h1>
<p>You asked for <code>${request.url}</code></p>`);
response.end();
});
server.listen(8000);
console.log("Listening! (port 8000)");
这是向服务器发出请求的代码:
const {request} = require("http");
let requestStream = request({
hostname: "localhost",
port: "8000",
path: "/index.html",
method: "GET",
headers: {Accept: "text/html"}
}, response => {
console.log("the server responded with "+ response.body);
});
requestStream.end();
如您所见,我试图获取服务器的响应内容:
response.write(`
<h1>Hello!</h1>
<p>You asked for <code>${request.url}</code></p>`);
这样做:
response => {
console.log("the server responded with "+ response.body);
但是它只在控制台中返回“ undefined”,我想知道我要做什么:
`
<h1>Hello!</h1>
<p>You asked for <code>${request.url}</code></p>`
从响应中
当我在服务器上使用CURL http://localhost:8000/index.html
时,会收到这样的响应,这就是我想要得到的。
我也尝试了类似的操作:
const {request} = require("http");
let requestStream = request({
hostname: "localhost",
port: "8000",
path: "/index.html",
method: "GET",
headers: {Accept: "text/html"}
}, response => {
let test= "";
response.on("data", chunk =>{
test = test + chunk.toString();
})
console.log("the server responded with "+ test);
});
requestStream.end();