node路由(访问页面)

如何使用node定义 '/'路由

创建router1.js

代码如下:

req.url就是请求的url地址也就是localhost:8080

pathname是8080后面的参数(8080:/user)

url.parse就是解析req.url

const http = require('http')
const url = require('url')

http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html;utf-8' }) //请求头部信息
    if (req.url !== '/favicon.ico') {
        var pathName = url.parse(req.url).pathname
        console.log(pathName)
    }
    res.end() //结束
}).listen(8080, () => {
    console.log('服务启动成功')
})

 控制台打印出 '/' 

url地址输入'/login'就输出'/login'

如何去除'/',,使用正则replace(/\//,'')

代码如下:

var pathName = url.parse(req.url).pathname.replace(/\//, '')

这样就可以自定义了

  或者改成

var pathName = url.parse(req.url).pathname.substr(1)

创建router.js文件

里面内容如下:

module.exports = {
    login: (req, res) => {
        res.write('登录页面')
    },
    register: (req, res) => {
        res.write('注册页面')
    },
    error: (req, res) => {
        res.write('404页面')
    }
}

把router.js引入到router1.js代码如下:

const http = require('http')
const url = require('url')
const router = require('./module/router')

http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' }) //请求头部信息
    if (req.url !== '/favicon.ico') {
        var pathName = url.parse(req.url).pathname.substr(1)
        console.log(pathName)
        try {
            router[pathName](req, res)
        } catch (err) {
            router.error(req, res)
        }
    }
    res.end() //结束
}).listen(8080, () => {
    console.log('服务启动成功')
})

这样就可以自定义路由了,文字显示在浏览器上

如何显示图片:先读取该文件夹下的图片路径,然后赋值给/img路由

把Content-type : image/jpeg

就可以了

如果读取html文件

把Content-type : text/html

如果读取json文件

把Conten-type : appliaction/json

猜你喜欢

转载自blog.csdn.net/qq_43390721/article/details/86480517
今日推荐