如何使用nodeJs制作本地服务器?

时间:2018-10-13 13:20:10

标签: javascript node.js

我正在尝试使用nodeJs创建本地服务器,但是它不起作用。

尝试了什么

var http = require('http');

http.createServer(function(req, res) {
    res.write('Hello');
    req.end();
}).listen(8080);

2 个答案:

答案 0 :(得分:0)

回调中的Key(代表响应)是res。将所需的所有内容(标题,正文)写入流后,必须像这样结束它:

Stream

您拥有的是res.end(); 。 使用req.end()代替req是您的错误。

此外,由于在这个人为的示例中只写了一行,所以可以写缓冲区并一次性结束流:

res

Docs for response.end

答案 1 :(得分:0)

使用response.end时要小心!

What is the difference between response.end() and response.send()?

response.end()将始终发送HTML字符串,而response.send()可以发送任何对象类型。以您的示例为例,两者都将达到目的,因为您正在发送HTML字符串“ hello”,但是在继续构建服务器时请牢记这些注意事项!

var http = require('http');

//Example with response.end()
http.createServer(function(request, response) {
    response.end('Hello');
}).listen(8080);

//Example with response.send()
http.createServer(function(request, response) {
    response.send('Hello');
}).listen(8080);

//Example with res.send() object
http.createServer(function(request, response) {
    response.send({ message: 'Hello', from: 'Happy Dev' });
}).listen(8080);