处理请求路径的分发

Node.js————处理请求路径的分发

http.createServer()方法中回调函数的参数request和response:
1.request对象是http.IncomingMessage 类的实例对象
2.response对象是http.ServerResponse 类的实例对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const http = require('http')
http.createServer((request, response) => {
    //request.url可以获取URL中端口之后的路径(即192.168.1.105:3000之后的部分)
    if(request.url.startsWith("/index")){
        // response.write()向客户端响应内容,可以执行多次
        response.write('Hello ')
        response.write('World')
        response.write('!')
        //response.end()方法用来结束响应,只能执行一次
        response.end('index')
    }else if(request.url.startsWith("/about")){
        response.end('about')
    }else{
        response.end('no content')
    }
}).listen(3000,'192.168.1.105', () => {
    console.log('running...')
})


-->