node.js - Express 中的查询参数

标签 node.js express query-string

我正在尝试使用 Node.js 中的 Express 访问查询参数。出于某种原因,req.params 一直作为空对象出现。这是我在 server.js 中的代码:

const express    = require('express');
const exphbs     = require('express-handlebars');
const bodyParser = require('body-parser');
const https      = require('https');

//custom packages  ..
//const config  = require('./config');
const routes  = require('./routes/routes');


const port = process.env.port || 3000;


var app = express();

//templating engine Handlebars
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');





//connect public route
app.use(express.static(__dirname + '/public/'));


app.use(bodyParser.json());

//connect routes
app.use('/', routes);






app.listen(port,  () => {
    console.log( 'Server is up and running on ' + port );
});

这是我的路线文件:

//updated
const routes = require('express').Router();


routes.get('/', (req, res) => {
  res.render('home');
});



routes.post('/scan',  (req, res) => {
    res.status(200);

    res.send("hello");
});



routes.get('/scanned',  (req, res) => {

    const orderID = req.params;
    console.log( req );

    res.render('home', {
        orderID
    });
});

module.exports = routes;

当服务器启动并运行时,我导航到 http://localhost:3000/scanned?orderid=234。我目前在 routes.js 文件中的控制台日志显示一个空主体(无法识别 URL 中的 orderid 参数)。

最佳答案

请求中的

orderid为查询参数。它需要通过 req.query 对象而不是 req.params 来访问。使用以下代码访问请求中传递的 orderid:

const orderID = req.query.orderid

现在您应该能够获得在请求 url 中传递的 234 值。

或者尝试将路由 /scanned 的代码替换为以下代码:

routes.get('/scanned',  (req, res) => {

  const orderID = req.query.orderid
  console.log( orderID ); // Outputs 234 for the sample request shared in question.

  res.render('home', {
    orderID
  });
});

关于node.js - Express 中的查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43560557/

相关文章:

node.js - Node .js.如何在两个函数之间共享数组?有没有比较简单的方法

node.js - nginx 和 socket.io 解决方法

mysql - Nodejs-Express-Mysql : render view after post

node.js - 如何在MongoDB中的数组对象中查找包含字符串的集合记录?

c# - 查询字符串唯一字符串生成器?

php - 使用 REGEX 过滤/清理 QUERY_STRING 以防止 RFI 攻击

java - 发送查询参数时 POST 请求出现 I/O 错误

Node.js 检查控制台命令返回未定义的错误

python - 在 Nodejs 中使用 PythonShell 模块

node.js - 返回服务器错误 Jade not finding isLoggedIn undefined