search

Home  >  Q&A  >  body text

node.js - express无法获取req.params值?

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的值。

迷茫迷茫2785 days ago660

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-17 16:28:45

    Usually req.params to get the parameters in the path

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 16:28:45

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

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 16:28:45

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

    reply
    0
  • Cancelreply