如果要用nodejs启动一个本地服务的话。
首先确保本地安装了nodejs;可以使用 node -v来判断本地是否安装node(如果返回版本号则为安装了)。
接着在当前目录下新建文件 index.js或者也可以起其他的名字,这个文件就是服务器的入口文件。
//index.js
const http = require('http');
const hostname = '127.0.0.1';
//创建服务
const server = http.createServer((req,res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('hello,world');
});
//监听
server.listen(3001, hostname, () => {
console.log(`启动本地服务地址为:http"//${hostname}:3001/ `);
})
在这块我们用到了node内置的http模块。
然后在当前目录下执行这个文件 node index.js
这个时候你在浏览器里访问http://127.0.0.1:3001就会看到输出‘hello,world’。
这就是用nodejs起本地服务的全部过程。