繁体   English   中英

Express js - 无法从 url 获取查询参数(req.query 为空对象)

[英]Express js - cannot get query parameters from url (req.query is an empty object)

我知道这里这里都提到了这个话题,但它对我不起作用。

我正在尝试使用req.query从 URL 获取参数。 在我的server.js文件中,我有这个:

app.get('/reset-pass', function(req,res) {
    console.log(req.url);
    console.log(req.query);
})

当我输入 URL 例如http://localhost:3000/reset-pass?email=anything时,服务器控制台输出:

/reset-pass
[Object: null prototype] {}

当我从http://localhost:4001/reset-pass获取时,浏览器控制台输出空的 object:

data {
    "query": {}
}

如您所见,我在4001端口上运行我的节点服务器,在3000上运行客户端站点(因为我在该端口上运行 React)并且它在执行POST请求或重定向时运行良好,但在GET情况下它不返回查询参数。 任何奇怪的#都不会出现在我的路径中(或者我只是不知道)。

它出什么问题了?

尝试

req.query.email

希望这可以解决您的问题

您的代码中一定还有另一个问题。 因为我和你一样测试过,完全一样的路线。

router.get('/reset-pass', function (req, res) {
    console.log(req.url);
    console.log(req.query);
    res.json({
        url: req.url,
        query: req.query,
    });
});

返回为:

{
    "url": "/reset-pass?email=anything",
    "query": {
        "email": "anything"
    }
}

和 console.log 为: 在此处输入图像描述

没关系。 这个操作没有问题。 您应该检查代码的其他部分。

我已经弄清楚出了什么问题。

服务器的一切都很好。 当我使用服务器端口而不是客户端端口( http://localhost:4001/reset-pass?email=anything )在浏览器中输入查询时,服务器终端中的 console.log 会正确输出所有内容(如douscriptist所说)或页面上(例如使用res.send() )它显示预期的数据。

问题在于在 React 中显示 URL 参数(在客户端视图中)。

在这种情况下,尝试获取数据是不必要的。 我应该使用React Router指定这样的路由:

应用程序.js

<Router>
    <Switch>
        <Route exact path="/" component={Main} />
        <Route path="/reset-pass">
            <Route path="/:email" component={ResetPass} />
        </Route>
        <Route component={NoMatch} />
    </Switch>
</Router>

然后在使用匹配位置的 ResetPass.js 中,我可以显示查询参数。 对于快速解析 URL 字符串,我添加了查询字符串模块

ResetPass.js

import React, { Fragment } from "react";
import queryString from "query-string";

const ResetPass = ({ match, location }) => {
    console.log("MATCH", match);
    console.log("LOCATION", location);
    const parsed = queryString.parse(location.search);
    return (
        <Fragment>
            <p>Params: {parsed.email}</p> {/* => Params: anything*/}
        </Fragment>
    );
};

export default ResetPass;

因此,当我输入 URL http://localhost:3000/reset-pass?email=anything时,console.log(在浏览器中)会返回:

MATCH {path: "/:email", url: "/reset-pass", isExact: true, params: {email: "reset-pass"}}
LOCATION {pathname: "/reset-pass", search: "?email=anything", hash: "", state: undefined}

我希望我已经正确解释了一切。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM