const http = require('http')
const url = require('url')
const server = http.createServer()
server.on('request', (req, res) => {
console.log(url.parse(req.url))
res.end('ok')
})
server.listen(3000,() => {
console.log(' 服务器启动成功')
})
服务器启动成功
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?id=123456&name=zhangsan&age=20',
query: 'id=123456&name=zhangsan&age=20', // 请求参数
pathname: '/list', // 请求地址
path: '/list?id=123456&name=zhangsan&age=20',
href: '/list?id=123456&name=zhangsan&age=20'
}
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/favicon.ico',
path: '/favicon.ico',
href: '/favicon.ico'
}
设置url.parse(req.url,true),可以进一步将query解析为 对象,就可以得到id、name、age这些参数了
const http = require('http')
const url = require('url')
const server = http.createServer()
server.on('request', (req, res) => {
console.log(url.parse(req.url, true))
res.end('ok')
})
server.listen(3000,() => {
console.log(' 服务器启动成功')
})
服务器启动成功
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: '?id=123456&name=zhangsan&age=20',
query: [Object: null prototype] {
id: '123456',
name: 'zhangsan',
age: '20'
},
pathname: '/list',
path: '/list?id=123456&name=zhangsan&age=20',
href: '/list?id=123456&name=zhangsan&age=20'
}
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: [Object: null prototype] {
},
pathname: '/favicon.ico',
path: '/favicon.ico',
href: '/favicon.ico'
}
const {
pathname, query } = url.parse(req.url, true)