这是代码部分
//1.导入http模块
const http = require('http')
//2.创建实例
const server = http.createServer()
//3.注册监听事件
server.on('request', (res, req) => {
//3.1获取请求的URL地址
const url = req.url
//3.2设置默认的响应内容为404
let content = '404 NOT FOUND'
//3.3判断用户请求是否为 / 或/index.html
//3.4判断用户请求是否为 /about.html
if (url == '/' || url === '/index.html') {
content = '<h1>首页</h1>'
} else if (url === '/about.html') {
content = '<h1>关于页面</h1>'
}
//3.5设置content-type属性,防止中文乱码
res.setHeader('Content-Type', 'text/html;charset=utf-8')
//3.6使用res.end()把内容响应给客户端
res.end(content)
})
server.listen(80, () => {
console.log('server running at http://127.0.0.1');
})
这是终端运行部分
server running at http://127.0.0.1
/Users/yangqing/VS code/6.Node. js/day2/code/04.根据不同的url响应不同的html内容.js:47
res.setHeader('Content-Type', 'text/html;charset=utf-8')
^
TypeError: res.setHeader is not a function
at Server.<anonymous> (/Users/yangqing/VS code/6.Node. js/day2/code/04.根据不同的url响应不同的html内容.js:47:7)
at Server.emit (node:events:513:28)
at parserOnIncoming (node:_http_server:1072:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17)
server.on('request', (res, req) => {
这一行res, req顺序反了,应该是 req, res