Express解析POST请求参数

Express解析POST请求参数

标签(空格分隔): Node.js


[TOC]

添加json解析中间件

在app.js文件中

var app = require('express')();
var path = require('path');
var express = require('express');
// 引入json解析中间件
var bodyParser = require('body-parser');
// 添加json解析
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

// 允许所有的请求形式
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

//  将静态文件(html文件,图片,等资源放到static目录,该目录可以自己创建)
 app.use(express.static(path.join(__dirname, 'static')));

路径请求及对应的获取路径有以下几种形式

req.query

// GET /search?q=tobi+ferret  
req.query.q  
// => "tobi ferret"  

// GET /shoes?order=desc&shoe[color]=blue&shoe[type]=converse  
req.query.order  
// => "desc"  

req.query.shoe.color  
// => "blue"  

req.query.shoe.type  
// => "converse"  

req.body

// POST user[name]=tobi&user[email][email protected]  
req.body.user.name  
// => "tobi"  

req.body.user.email  
// => "[email protected]"  

// POST { "name": "tobi" }  
req.body.name  
// => "tobi"  

req.params

// GET /user/tj  
req.params.name  
// => "tj"  

// GET /file/javascripts/jquery.js  
req.params[0]  
// => "javascripts/jquery.js" 

req.param(name)

// ?name=tobi  
req.param('name')  
// => "tobi"  

// POST name=tobi  
req.param('name')  
// => "tobi"  

// /user/tobi for /user/:name   
req.param('name')  
// => "tobi"  

你可能感兴趣的:(Express解析POST请求参数)