路由
原创2026/3/5小于 1 分钟

我们要为路由提供请求的URL和其他需要的GET及POST参数,随后路由需要根据这些数据来执行相应的代码。
const http = require('http')
const url = require('url')
const server = http.createServer(function (req, res) {
const pathname = url.parse(req.url).pathname
if (pathname == '/') {
res.end('hello')
} else if (pathname == '/getList') {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' })
res.write(JSON.stringify({ recrods: [{ name: 'fyx' }] }))
res.end()
} else {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' })
res.end('默认值')
}
})
server.listen('3030', function () {
console.log('服务器正在监听3030端口')
})整理:
index.js
const http = require('http')
const url = require('url')
const router = require('./router')
const server = http.createServer(function (req, res) {
const pathname = url.parse(req.url).pathname
router(pathname, res)
})
server.listen('3030', function () {
console.log('服务器正在监听3030端口')
})router.js
module.exports = (pathname, res) => {
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' })
if (pathname == '/') {
res.end('hello')
} else if (pathname == '/getList') {
res.write(JSON.stringify({ recrods: [{ name: 'fyx' }] }))
res.end()
} else {
res.end('默认值')
}
}至此,本章节的学习就到此结束了,如有疑惑,可对接技术客服进行相关咨询。