Express req.query 始终为空

Chl*_*e.C 5 node.js express

我正在使用这样的快速路由,我希望我的 url 最初包含查询字符串。

app.get('/', function(req, res){
  res.render('index', {});
});
app.get('/us01', function(req, res){
  console.log('query: '+JSON.stringify(req.query));
  res.render('templates/us01', {});
});
app.get('/benchmark', function(req, res){
  res.render('templates/benchmark', {});
});
Run Code Online (Sandbox Code Playgroud)

但是,无论我在 /us01 之后附加什么查询字符串,我都不会打印我的查询字符串。例如,"localhost:9200/us01?a=1" req.query 应该得到我 {a:1},对吗?这是普遍现象吗?我在这里缺少什么?

我的 app.js

"use strict";
var express = require('express');
var expApp = express();
var http = require('http').Server(expApp);
var path = require('path');
var bodyParser = require('body-parser');

// all environments
expApp.set('port', process.env.PORT || 5555);
expApp.set('views', __dirname + '/views');
expApp.set('view engine', 'ejs');
expApp.use(bodyParser.urlencoded({ extended: true }));
expApp.use(bodyParser.json());
expApp.use(express.static(path.join(__dirname, 'public')));
//----------------ROUTES--------------------------//
require("./routes/route.js")(expApp);

http.listen(expApp.get('port'), function(){
    console.log('Node-Server listening on port ' + expApp.get('port'));
});
Run Code Online (Sandbox Code Playgroud)

我的 indexController.js 有:

$stateProvider
        .state('us01', {
            url: '/us01',
            templateUrl: '/us01'
        }).state('benchmark', {
            url: '/benchmark',
            templateUrl: '/benchmark'
        })....
Run Code Online (Sandbox Code Playgroud)

jfr*_*d00 5

这个简单的代码:

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

app.get('/us01', function(req, res) {
    console.log(req.query);
    res.send("ok");
});

app.listen(80);
Run Code Online (Sandbox Code Playgroud)

然后,通过访问http://localhost/us01?a=1在控制台中生成以下输出:

{ a: '1' }
Run Code Online (Sandbox Code Playgroud)

或者,如果我使用:

console.log('query: ' + JSON.stringify(req.query));
Run Code Online (Sandbox Code Playgroud)

然后,我在控制台中看到:

query: {"a":"1"}
Run Code Online (Sandbox Code Playgroud)

所以,显然您的代码中还有其他问题。


"localhost:9200/us01?a=1" req.query 应该得到我 {a:1},对吗?

query: {"a":"1"}如果您显示的代码正在本地主机的端口 9200 上运行,它应该会帮助您。

这是常见的事情吗?

不。除了您显示的代码之外,还有其他东西被破坏了,因为那段代码没有任何问题。

我在这里缺少什么?

要检查的事项:

  1. 当您到达任何预期路线时,您是否在控制台中得到任何输出?
  2. 您能证明您的服务器正在运行并且您的浏览器正在访问您的路由处理程序吗?
  3. 如果你这样做console.log(req.query),你会得到什么输出?
  4. 您是否绝对确定已杀死所有先前的服务器并启动与您显示的代码相对应的服务器?人们有时会被仍在运行的服务器的早期版本所愚弄,该版本实际上并不包含他们认为正在运行的代码。
  5. 您是否 100% 确定您正在与您正在使用的 URL 中的端口相匹配的所需端口上运行服务器?
  6. 当所有其他方法都失败时,有时计算机重新启动将确保没有任何先前版本仍在运行。

  • @Chloe.C - 好吧,您需要发布您自己的答案或删除您的问题,因为它不应该在没有接受的答案的情况下悬而未决。 (2认同)