NodeJS 无法在express中间件中获取请求参数

xmq68pz9  于 2023-05-28  发布在  Node.js
关注(0)|答案(4)|浏览(257)

我无法读取中间件中的任何请求参数。我有一个最小的express web服务器,看起来像

'use strict';

var express = require('express');
var app = express();

//middleware
function userMiddleware(req, res, next) {
  console.log('user came in. Hello ' + req.param('name'));
  next();
}

//register middleware
app.use('/user', userMiddleware)

// routes
app.get('/user/:name', function(req, res) {
  res.send('username : ' + req.params.name);
});

app.listen(3000);
console.log("listening on 3000...");

当我尝试访问localhost:3000/user/威廉姆斯时,我希望在日志中看到:

user came in. Hello williams

但我明白了

user came in. Hello undefined

我是否应该包含任何其他中间件,以便在中间件中填充req.params?我使用express@3.3.4

np8igboo

np8igboo1#

我认为app.param()在这种情况下是非常规的,不是很直观。因为我已经有了表示中间件的函数,我可以做:

//middleware
function userMiddleware(req, res, next) {
  console.log('user came in. Hello ' + req.params.name);
  next();
}

// routes
app.get('/user/:name', userMiddleware, function(req, res) {
  res.send('username : ' + req.params.name);
});
mqxuamgl

mqxuamgl2#

编辑

下面的答案是不正确的。您实际上并不需要jsonurlencoded中间件来获取路由参数-它们只需要req.queryreq.body工作。正如你所知道的(因为你是那里的海报之一),你在评论中提供的链接描述了这个问题:
https://github.com/strongloop/express/issues/2088
问题是您试图在路由参数存在之前访问它们-中间件在路由之前运行。一个解决方案是使用该链接中建议的app.param()(而不是您的userMiddleware):

app.param('name', function(req, res, next, name) {
    console.log('user came in. Hello ' + name);
    next();
});

请注意,这将在所有路由中找到name参数,因此您可能希望将参数命名得更具体一些,例如username。如果您想缩小范围,也可以检查req.url的开头。
顺便说一句,通常应该避免像在原始代码中那样使用req.param();引用Express文档:Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.

老答案

把它留在这里,因为它包含的信息可能在其他情况下有用...
我相信你需要添加这个中间件,以使GET和POST变量可用:

.use(express.json()) //support JSON-encoded bodies
.use(express.urlencoded()) //support URL-encoded bodies

并且:

.use(express.methodOverride())

如果您还需要在所有浏览器中使用HTTP动词,如PUT或DELETE。
您可以使用bodyparser而不是jsonurlencoded,但由于文件上传,这将是一个安全漏洞。参见http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html。此外,bodyparser在Express 4中被弃用。注意,如果你想支持文件上传,你需要使用额外的中间件(一个好的选择是https://www.npmjs.org/package/multer)。

whitzsjs

whitzsjs3#

我遇到的最好的解决方案是使用带有all方法的路由器。
例如:

function middleware(req, res, next) {
  console.log('Parameters - ', req.params)
}

let router = require('express').Router
router.route('/test')
   .all(middleware)
   .get((req, res, next) => {
     // handle route
   })
os8fio9y

os8fio9y4#

//I know this question is old but here is my way to solve it in the prtesent

import middlewareExample from "archiveExample.js";

router.put("/example/:id", 
  (req,res,next)=>{res.locals.params=req.params; next();},
  middlewareExample,
  async(req,res)=>{
  //Some code...
});

//Now you have req.params in res.locals.params

相关问题