I know this topic was mentioned here and here but it didn't work for me.
I'm trying to get parameters from URL using req.query
. In my server.js
file I've got this:
app.get('/reset-pass', function(req,res) {
console.log(req.url);
console.log(req.query);
})
When I'm entering URL eg http://localhost:3000/reset-pass?email=anything
, server console outputs this:
/reset-pass
[Object: null prototype] {}
and when I fetch from http://localhost:4001/reset-pass
, browser console outputs empty object:
data {
"query": {}
}
As you can see I run my node server on 4001
port and client site on 3000
(because I'm running React on that port) and it's working well doing POST
requests or redirects, but in GET
case it doesn't return query params. Any weird #
do not appear in my path (or I just don't know it).
What's wrong with it?
Try
req.query.email
Hope this solves your issue
There must be another problem in your code. Because i just tested as you did, totally same route.
router.get('/reset-pass', function (req, res) {
console.log(req.url);
console.log(req.query);
res.json({
url: req.url,
query: req.query,
});
});
Returns as:
{
"url": "/reset-pass?email=anything",
"query": {
"email": "anything"
}
}
And it's ok. There is no problem with this operation. You should check other parts of your code.
I've figured out what was wrong.
Everything was perfectly fine with server. When I typed query in browser using server port, not client port ( http://localhost:4001/reset-pass?email=anything
), console.log in server terminal outputs everything correctly (as douscriptist said) or on page (eg using res.send()
) it displays expected data.
Trying to fetch data was just unnecessary in this case. I should have used React Router specifying routes like this:
<Router>
<Switch>
<Route exact path="/" component={Main} />
<Route path="/reset-pass">
<Route path="/:email" component={ResetPass} />
</Route>
<Route component={NoMatch} />
</Switch>
</Router>
And then in ResetPass.js using match and location I'm able to display query parameters. For quick pars URL string I've added query-string module
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;
So when I enter URL http://localhost:3000/reset-pass?email=anything
, console.log (in browser) returns this:
MATCH {path: "/:email", url: "/reset-pass", isExact: true, params: {email: "reset-pass"}}
LOCATION {pathname: "/reset-pass", search: "?email=anything", hash: "", state: undefined}
I hope that I've explained everything correctly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.