Express获取请求参数

来源:互联网 发布:软考程序员考试大纲 编辑:程序博客网 时间:2024/06/09 22:53

HTTP请求的参数无外乎这么几种
1. query参数
2. form参数
3. path参数
4. matrix参数
5. cookie参数
6. header参数
这六种参数中,express暂不提供api直接获取matrix参数。其余五种都支持。但是header参数无法枚举。
简单介绍下这些参数的获取

  1. Query参数 Req.query
  2. Form参数 Req.body,需要用到插件body-parser,代码:
var BodyParser= require('body-parser');app.use(BodyParser.urlencoded({ extended: true })); 
  1. path参数 Req.params
  2. matrix参数 无
  3. cookie参数 Req.cookies,需要用到插件cookie-parser,代码:
var CookieParser = require("cookie-parser");app.use(new CookieParser());
  1. header参数 Req.get(name)
    我写了一段小代码试了下五种参数的获取:
var Express = require("express");var app = new Express();// query paramapp.get("/search",function(req,res){    res.json(req.query);});// form paramvar BodyParser= require('body-parser');app.use(BodyParser.urlencoded({ extended: true }));app.post("/search",function(req,res){    res.json(req.body);});// path paramapp.get("/search/:path.html",function(req,res){    res.json(req.params);});// cookie paramvar CookieParser = require("cookie-parser");app.use(new CookieParser());app.put("/search",function(req,res){    res.json(req.cookies);});// header paramapp.patch("/search",function(req,res){    res.send(req.get('Content-Type'));});app.listen(8080);

测试工具可以使用Opera浏览器的RESTMAN插件。