1.9 Node.js路由 🎉
...小于 1 分钟
1.9 Node.js路由 🎉
我们要为路由提供请求的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端口')
})
整理:
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端口')
})
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('默认值')
}
}
Powered by Waline v2.15.7