node+express下获取请求参数

本文详细介绍了如何在Express.js中处理HTTP请求,包括GET和POST请求的参数获取方式,以及如何获取请求头信息、路由信息等其他相关信息。

 

针对Express的版本4.X

Get


query参数的获取

url假设:http://localhost:3000/users/zqzjs?name=zhaoqize&word=cool&job[st]=web

路由的定义:

router.get('/:name', function(req, res, next) {


})

1.获取?name=zhaoqize这样的参数

req.query.name

2.获取&job[st]=web这样的参数

req.query.job.st

3.获取?name=zhaoqize参数的另外一种写法(4.x版本中该方法已被废弃)

req.param('name')

4.获取所有参数

JSON.stringify(req.query)

具体代码:

//http://localhost:3000/users/zqzjs?name=zhaoqize&word=cool&job[st]=web
//http://localhost:3000/users/zqzjs
router.get('/:name', function(req, res, next) {
  //4.版本中已被废弃,不建议使用
  req.param('name')
  console.log(JSON.stringify(req.query) || '')
  //获取get请求参数
  var _html = "Params"+
              "<p><strong>req.params:</strong>"+(JSON.stringify(req.params) || '')+"</p>" +
              "<p><strong>req.params.name:</strong>"+(req.params.name || '')+"</p>" +
              "Query:" +
              "<p><strong>req.query:</strong>"+(JSON.stringify(req.query) || '')+"</p>" +
              "<p><strong>req.query.name:</strong>"+(req.query.name || '')+"</p>" +
              "<p><strong>req.query.word:</strong>"+(req.query.word || '')+"</p>"+
              "<p><strong>req.query.job.st:</strong>"+(req.query.job.st || '')+"</p>" +
              "<p><strong>req.param('name'):</strong>"+(req.param('name') || '')+"</p>" ;
              


  res.send(_html);
});

结果:

[Get]
Params
req.params:{"name":"zqzjs"}


req.params.name:zqzjs


Query:
req.query:{"name":"zhaoqize","word":"cool","job":{"st":"web"}}


req.query.name:zhaoqize


req.query.word:cool


req.query.job.st:web


req.param('name'):zqzjs

Post


post的数据获取

Form Data 
 pName:zqz
 pWord:job

1.获取需要的query参数

req.body.pName

具体代码:

router.post('/postTest',function(req, res, next){
    var _html = "[Post]" +
                "<p><strong>req.body:</strong>"+(JSON.stringify(req.body) || '')+"</p>" +
                "<p><strong>req.body.name:</strong>"+(req.body.pName || '')+"</p>" +
                "<p><strong>req.body.name:</strong>"+(req.body.pWord || '')+"</p>";
    res.send(_html);
})

结果:

[Post]
req.body:{"pName":"zqz","pWord":"job"}


req.body.name:zqz


req.body.name:job

其他信息


获取请求的头信息

使用:req.header(field)

//http://localhost:3000/users/requestInfo/get
router.get('/requestInfo/get',function(req, res, next){
    var _html = "";
    _html += "[Accept] "+req.header('Accept')+"<br/>"
    _html += "[Accept-Encoding] "+req.header('Accept-Encoding')+"<br/>"
    _html += "[Accept-Language] "+req.header('Accept-Language')+"<br/>"
    _html += "[Cache-Control] "+req.header('Cache-Control')+"<br/>"
    _html += "[Connection] "+req.header('Connection')+"<br/>"
    _html += "[Cookie] "+req.header('Cookie')+"<br/>"
    _html += "[Host] "+req.header('Host')+"<br/>"
    _html += "[If-None-Match] "+req.header('If-None-Match')+"<br/>"
    _html += "[Upgrade-Insecure-Requests] "+req.header('Upgrade-Insecure-Requests')+"<br/>"
    _html += "[User-Agent] "+req.header('User-Agent')+"<br/>"
    res.send(_html);
})


//结果:
[Accept] text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
[Accept-Encoding] gzip, deflate, sdch, br
[Accept-Language] zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4,ja;q=0.2
[Cache-Control] max-age=0
[Connection] keep-alive
[Cookie] Hm_lvt_4f16d955a2236fc6ca7287644ecc9d79=1480576847,1481166685
[Host] localhost:3000
[If-None-Match] W/"23b-OjTNcZfCLTvw659CYGlLrA"
[Upgrade-Insecure-Requests] 1
[User-Agent] Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36

route

使用:req.route

//http://localhost:3000/users/router/get
router.get('/router/get',function(req, res, next){
    res.send(req.route);
})


//结果:


{
path: "/router/get",
stack: [
{
name: "<anonymous>",
keys: [ ],
regexp: { },
method: "get"
}
],
methods: {
get: true
}
}

cookies

使用:req.cookies

//http://localhost:3000/users/cookies/get
router.get('/cookies/get',function(req, res, next){
    res.send(req.cookies);
})


//结果:
{
Hm_lvt_4f16d955a2236fc6ca7287644ecc9d79: "1480576847,1481166685"
}

hostname

使用:req.hostname

//http://localhost:3000/users/hostname/get
router.get('/hostname/get',function(req, res, next){
    res.send(req.hostname);
})


//结果:
localhost

ip

使用:req.ip

//http://localhost:3000/users/ip/get
router.get('/ip/get',function(req, res, next){
    res.send(req.ip);
})


//结果:
::1

originalUrl

使用:req.originalUrl

//http://localhost:3000/users/originalUrl/get
router.get('/originalUrl/get',function(req, res, next){
    res.send(req.originalUrl);
})


//结果:
/users/originalUrl/get

protocol

使用:req.protocol

//http://localhost:3000/users/protocol/get
router.get('/protocol/get',function(req, res, next){
    res.send(req.protocol);
})


//结果:
http

secure

使用:req.secure

说明:用来判断协议是否安全,如果是https,返回的就是true

//http://localhost:3000/users/secure/get
router.get('/secure/get',function(req, res, next){
    res.send(req.secure);
})


//结果:
false

xhr

使用:req.xhr

说明:判断是否是异步请求

//http://localhost:3000/users/xhr/get
router.get('/xhr/get',function(req, res, next){
    res.send(req.xhr);
})


//结果:
false

<think>我们正在使用Node.js的Express框架,获取请求参数主要有三种方式: 1. 查询字符串参数(GET请求):通过req.query获取。 2. 路由参数(动态路由):通过req.params获取。 3. 请求参数(POST/PUT等请求):需要中间件(如express.json()或express.urlencoded())解析,然后通过req.body获取。 下面是一个示例代码,展示如何获取这三种参数: ```javascript const express = require('express'); const app = express(); // 中间件用于解析请求体 app.use(express.json()); // 解析JSON格式的请求体 app.use(express.urlencoded({ extended: true })); // 解析URL编码格式的请求体 // 示例路由:获取查询字符串参数 app.get('/search', (req, res) => { const keyword = req.query.keyword; // 例如:/search?keyword=express res.send(`搜索关键词: ${keyword}`); }); // 示例路由:获取路由参数 app.get('/user/:userId', (req, res) => { const userId = req.params.userId; // 例如:/user/123 res.send(`用户ID: ${userId}`); }); // 示例路由:获取请求参数(POST请求) app.post('/login', (req, res) => { const username = req.body.username; const password = req.body.password; res.send(`用户名: ${username}, 密码: ${password}`); }); app.listen(3000, () => { console.log('服务器运行在 http://localhost:3000'); }); ``` 注意:对于POST请求,必须使用相应的中间件来解析请求体,否则req.body将为空。 §§相关问题§§ 1. 在Express中,如何处理文件上传并获取上传的文件? 2. 除了query、params和body,Express请求对象还有哪些常用属性用于获取请求信息? 3. 如何验证和清理用户通过请求参数提交的数据? 4. 在Express中,如何获取HTTP请求头信息? 5. 如果请求体是XML格式,Express如何解析? </think>在 Node.js 的 Express 框架中,获取请求参数主要有以下三种方式: ### 1. **查询字符串参数(URL 参数)** 使用 `req.query` 获取 URL 中 `?` 后的键值对参数 **示例**: ```javascript // 请求:GET /users?name=John&age=30 app.get('/users', (req, res) => { const name = req.query.name; // "John" const age = req.query.age; // "30" }); ``` ### 2. **路由参数(路径参数)** 在路由路径中用 `:param` 定义,通过 `req.params` 获取 **示例**: ```javascript // 请求:GET /users/42 app.get('/users/:id', (req, res) => { const userId = req.params.id; // "42" }); ``` ### 3. **请求参数(Body 数据)** 需要中间件解析请求体,常用 `express.json()` 和 `express.urlencoded()` **示例**: ```javascript app.use(express.json()); // 解析 JSON 格式 app.use(express.urlencoded({ extended: true })); // 解析表单格式 // 请求:POST /login { "email": "test@example.com", "password": "123" } app.post('/login', (req, res) => { const email = req.body.email; // "test@example.com" const password = req.body.password; // "123" }); ``` ### 完整示例代码 ```javascript const express = require('express'); const app = express(); app.use(express.json()); // 解析 JSON 请求体 app.use(express.urlencoded({ extended: true })); // 解析表单请求体 // 1. 获取查询字符串参数 app.get('/search', (req, res) => { const keyword = req.query.q; // ?q=nodejs res.send(`搜索关键词: ${keyword}`); }); // 2. 获取路由参数 app.get('/product/:id', (req, res) => { const productId = req.params.id; // /product/101 res.send(`产品ID: ${productId}`); }); // 3. 获取请求参数 app.post('/register', (req, res) => { const { username, email } = req.body; // {username: "Tom", email: "tom@example.com"} res.send(`用户 ${username} 注册成功,邮箱: ${email}`); }); app.listen(3000, () => console.log('服务器运行中')); ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值