1.通过新版url模块解决路由后面带参数的问题
有时候路由会带参数什么的 以下就是这个问题
这时候则通过新版url模块来解决
//引入模块
const http = require('http')
const serve = http.createServer()
serve.on('request', (req, res) => {
//赋值 方便之后写代码
const newVersion =new URL(req.url,'http://localhost:3000')
const pathUrl=newVersion.pathname
//输出 可以看看里面是什么
console.log(pathUrl)
//错误提示
let content = '<h1>404 not found</h1>'
if (pathUrl == '/' || pathUrl == "/index") {
content = '<h1>这是首页</h1>'
}
if (pathUrl == '/favicon.ico' ) {
return
}
if (pathUrl == '/about') {
content = '<h1>这是关于页面</h1>'
}
//请求头 以utf-8解析模板
res.setHeader('Content-Type', 'text/html;charset=utf-8')
//结束 并在里面返回模板
res.end(content)
})
//设置服务器地址
serve.listen('3000', () => {
console.log('http://localhost:3000')
})
2.通过新版url获取前端传的参数
serve.on('request', (req, res) => {
//赋值 方便之后写代码
const newVersion =new URL(req.url,'http://localhost:3000')
//拿到处理过的路径
const pathUrl=newVersion.pathname
//循环newVersion.searchParams
for(let [key,value] of newVersion.searchParams){
//输出拿到的值
console.log(key,value)
}
//错误提示
let content = '<h1>404 not found</h1>'
if (pathUrl == '/' || pathUrl == "/index") {
content = '<h1>这是首页</h1>'
}
if (pathUrl == '/favicon.ico' ) {
return
}
if (pathUrl == '/about') {
content = '<h1>这是关于页面</h1>'
}
//请求头 以utf-8解析模板
res.setHeader('Content-Type', 'text/html;charset=utf-8')
//结束 并在里面返回模板
res.end(content)
})
//设置服务器地址
serve.listen('3000', () => {
console.log('http://localhost:3000')
})
基本上跟第一步没什么区别 以下就是多出来的代码
const newVersion =new URL(req.url,'http://localhost:3000')
for(let [key,value] of newVersion.searchParams){
console.log(key,value)
}