Node.js中的express框架獲取參數

express獲取參數有三種方法:php

  1. req.query  適合 http://localhost:3000/form?num=8888
  2. req.body   適合http://localhost:3000/form,而後Post一個num爲tinyphp
  3. req.params  適合獲取form後的num:http://localhost:3000/form/num

 

1、GEThtml

 app.jsjquery

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.htmlexpress

<!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>

 

 

2、POSTnpm

解析post數據須要用到body-parserjson

npm body-parser --save

 app.jsapp

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.htmlpost

<!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>

 

 

3、獲取路徑ui

app.jsurl

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);

相關文章
相關標籤/搜索