欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

获取请求地址和参数(url模块的使用)

程序员文章站 2023-12-31 18:02:28
url 模块——url.parse( )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.lo...

url 模块——url.parse( )

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(' 服务器启动成功')
})
  • 在命令行运行上述代码
  • 通过浏览器发出:http://127.0.0.1:3000/list?id=123456&name=zhangsan&age=20
    的请求时,服务器端会将请求进行解析,可以得到请求地址以及请求参数
服务器启动成功
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'
}
  • 可以通过对对象结构来得到请求地址pathname以及请求参数对象query
const { pathname, query } = url.parse(req.url, true)

本文地址:https://blog.csdn.net/qq_27575925/article/details/109236939

上一篇:

下一篇: