node.js - express无法获取req.params值?
迷茫
迷茫 2017-04-17 16:26:45
0
3
665
var express = require('express');
var bodyParser = require('body-parser')
var port = process.env.PORT || 3000
var app = express()
var path = require('path');
var mongoose = require('mongoose')
var _ = require('underscore')
var fs = require('fs');
var jsonParser = bodyParser.json()
var urlencodedParser = bodyParser.urlencoded({ extended: false })
mongoose.connect('mongodb://localhost/meetdb')

app.set('views', './views/pages')
app.set('view engine', 'jade')

app.use(urlencodedParser);
app.use(express.static(path.join(__dirname, 'public')))
app.listen(port)

// user 相关
app.post('/user/signup',function (req,res){
  console.log(req.params)
 console.log(req.body)
})

可以获取到req.body,但是无法获取到req.params。我看网上说的是可以同时获取query和body的值。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
刘奇

Usually req.params to get the parameters in the path

Ty80

As far as I understand, req.params only has parameters in parameterized paths. Do you want to get the parameters in the query string? req.params 只有在参数化的路径中的参数。你想取的是查询字符串中的参数吗?

查询字符串中的参数要用 req.query.

比如

    // server.js:
    app.post('/user/:id', function(req, res){
        console.log('req.params: ', req.params)
        console.log('req.query: ', req.query)
        console.log('req.body: ', req.body)
    })
// HTTP request:
POST /user/123?foo=1&bar=2
Content-Type: application/x-www-form-urlencoded

aaa=1&bbb=2

这样的请求,应该是要用 req.query.fooreq.query.bar 来获取 foo 和 bar 的值,最终打印出如下:

req.params:  { id: '123' }
req.query:  { foo: '1', bar: '2' }
req.body:  { aaa: '1', bbb: '2' }

话说这种问题 console.log

The parameters in the query string must use req.query.

For example rrreee rrreee Such a request should use req.query.foo and req.query.bar to obtain the values ​​​​of foo and bar. The final printout is as follows:

rrreee

Speaking of this problem, the efficiency of console.log is too slow, why not use breakpoints:

🎜🎜🎜🎜🎜 🎜Look how cool it is to use VSCode breakpoints to view variables. 🎜
刘奇

/user/signup Here /user/signup/:aaa you have params

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template