跳至主要內容

1.9 Node.js路由 🎉

刘春龙...小于 1 分钟NODEJSNODE后端nodejs

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端口')
})
上次编辑于:
贡献者: 刘春龙
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.7