nodejs笔记之搭建服务器

时间:2022-08-14 21:39:38

简单服务器搭建:

1.新建一个文件:app.js

2.加入实现服务器代码;

const http = require("http");
http.createServer(function(req,res){
res.writeHead(200,{"content-type":"text/html;charset=utf-8;"});
res.write("<h1>服务器搭建成功</h1>");
res.end();
}).listen(3001);

3.运行app.js;

node app.js

4. 浏览器访问;

在浏览器中输入:localhost:3001

总结:
分析Node.js 的 HTTP 服务器:
(1)第一行请求(require)Node.js 自带的 http 模块,并且把它赋值给 http 变量。
(2)接下来我们调用 http 模块提供的函数: createServer 。这个函数会返回 一个对象,这个对象有一个叫做 listen 的方法,这个方法有一个数值参数, 指定这个 HTTP 服务器监听的端口号。