express获取参数有三种方法:
- req.query 适合 http://localhost:3000/form?num=8888
- req.body 适合http://localhost:3000/form,然后Post一个num为tinyphp
- req.params 适合获取form后的num:http://localhost:3000/form/num
一、GET
app.js
var express = require(‘express‘); var app = express(); app.use(express.static(‘public‘)); //获取数据 app.get(‘/form‘, function(req, res) { var num = req.query.num; res.send("你获取的get数据为:" + num); }); //设置监听端口 app.listen(3000);
public/test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> </head> <body> <div id="box"></div> <form action="/form" method="get"> <input type="text" name="num" value="8888"> <input type="submit" value="提交"> </form> </body> </html>
二、POST
解析post数据需要用到body-parser
npm body-parser --save
app.js
var express = require(‘express‘); var app = express(); //引入body-parser var bodyParser = require(‘body-parser‘); app.use(express.static(‘public‘)); //需要use的 app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded //获取数据 app.post(‘/form‘, function(req, res) { var num = req.body.num; res.send("你获取的post数据为:" + num); }); //设置监听端口 app.listen(3000);
public/test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> </head> <body> <div id="box"></div> <form action="/form" method="post"> <input type="text" name="num" value="tinyphp"> <input type="submit" value="提交"> </form> </body> </html>
三、获取路径
app.js
var express = require(‘express‘); var app = express(); //获取数据 app.get(‘/form/:num‘, function(req, res) { var num = req.params.num; res.send("你获取到form/后的参数:" + num); }); //设置监听端口 app.listen(3000);
时间: 2024-10-25 13:46:48