NodeJS 最简单入门案例
例子,一个使用 Node.js 编写的 web服务器,响应返回 'Hello World':
const http = require('http');//获取http模块
const hostname = '127.0.0.1';//定义主机IP
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}/`);
});
要运行这个服务器,需将代码保存到一个名为 example.js 的文件,并使用 Node.js 执行:
$ node example.js
服务器运行在 http://127.0.0.1:3000/
转载请注明:少狼 – 敬畏知识的顽皮狗 » NodeJS 最简单入门案例
还没有人抢沙发呢~