- 接上代码,回调函数中加入参数如下,并调end()给前端传信息
const http = require('http');
// req: request, res: response
const server = http.createServer((req, res) => {
console.log('已经收到http请求');
res.end('hello world') // res返回信息给前端
})
server.listen(3000); // 可以监听http的请求了
console.log('http请求已经被监听,3000端口');
- 执行程序
- 打开localhost:3000
- 看下req的url是什么,代码如下:
const http = require('http');
// req: request, res: response
const server = http.createServer((req, res) => {
console.log('已经收到http请求');
const url = req.url;
console.log('url is', url)
res.end('hello world') // res返回信息给前端
})
server.listen(3000); // 可以监听http的请求了
console.log('http请求已经被监听,3000端口');
-
查看控制台,返回url:
注:favicon.ico是网站tab上的小图片,是浏览器的自发行为 -
如果访问localhost:3000/index.html,则url值为 /index.html,如下图