![使用node.js 文档里的方法写一个web服务器 使用node.js 文档里的方法写一个web服务器](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
刚刚看了node.js文档里的一个小例子,就是用 node.js 写一个web服务器的小例子
上代码 (*^▽^*)
//helloworld.js
// 使用node.js写一个服务器
const http=require('http'); const hostname='127.0.0.1'
const port=3000; const server = http.createServer((req,res)=>{
res.statusCode=200;
res.setHeader('Content-Type','text/plain');
res.end('Hello World\n');
}); server.listen(port,hostname,()=>{
console.log(`服务器运行在http://${hostname}:${port}/`);
});
然后在控制台输入 node helloworld.js ,然后将控制台显示的服务器运行地址复制到浏览器里,如果可以看到 Hello World 就表示服务器运行成功了(^-^)V
感觉这段代码封装的很严实,逻辑很清晰,但是不知道应该怎么用(ಥ_ಥ),以后知道了再来更新吧(*^▽^*)