以下是一个简单的配置http服务器的示例。
const http = require('http');
// 创建服务
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, {'Content-Type': 'text/plain'});
// 发送响应数据
res.end('Hello World\n');
});
// 启动服务
server.listen(8080, 'localhost', () => {
console.log('Server running at http://localhost:8080/');
});
在这个示例中,我们通过`http.createServer()`方法创建了一个http服务器,方法里面的回调函数用于处理请求和发送响应。该回调函数接受两个参数,一个是request对象,表示客户端的请求,另一个是response对象,用于发送响应给客户端。
在回调函数里面,我们通过`res.writeHead()`方法设置了响应头,将状态码设为200,内容类型设为text/plain。然后使用`res.end()`方法发送了一段文本作为响应数据。
最后,我们通过`server.listen()`方法指定服务器监听的端口和主机,并在回调函数里面输出一段提示信息。
运行以上代码后,你可以在浏览器中访问`http://localhost:8080/`,就能看到"Hello World"这个响应数据了。
查看详情
查看详情