[英]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"
}
}
沒關系。 這個操作沒有問題。 您應該檢查代碼的其他部分。
我已經弄清楚出了什么問題。
服務器的一切都很好。 當我使用服務器端口而不是客戶端端口( http://localhost:4001/reset-pass?email=anything
)在瀏覽器中輸入查詢時,服務器終端中的 console.log 會正確輸出所有內容(如douscriptist所說)或頁面上(例如使用res.send()
)它顯示預期的數據。
在這種情況下,嘗試獲取數據是不必要的。 我應該使用React Router指定這樣的路由:
<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 字符串,我添加了查詢字符串模塊
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.