Skip to content
Advertisement

req.query is empty and req.url is not complete using react router and express

When the page URL is http://localhost:3000/verify?token=something and I make a GET request using fetch, when I hit the server, req.url is “/verify” instead of “verify?token=something”, also the req.query object is empty

The client is running on port 3000 and the server on port 5000. I’m using a proxy in package.json on the client-side.

Have been scratching my head for some time now and can’t figure this out, so any help would be much appreciated

Client code:

App.js

import {BrowserRouter as Router, Route} from "react-router-dom";


function App() {

  return (
    <Router>
      <Navbar/>
      <Route exact path="/" component={Home}/>
      <UnPrivateRoute path="/verify" component={Verify}/>
    </Router>
  );
}

export default App;

Verify.jsx

import AuthService from "../api/auth";

const Verify = () => {
    const [message,setMessage] = useState(null);
    const [confirm,setConfirm] = useState(true);

    if(confirm){
        AuthService.verify().then(data =>{
            const {message} = data;
            setMessage(message);
        });
        setConfirm(false);
    }

    return(
        <div className="container">
            <h1>Verify</h1>
            {message ? <Message message={message}/> : null}
        </div>
    )
}

export default Verify;

auth.js

export default {
    verify: () => {
        return fetch("/user/verify")
            .then(res => res.json())
            .then(data => data);
    }
}

Server Code:

User.js

userRouter.get("/verify", (req, res) => {
    console.log(req.url);
    console.log(req.query);
});

Advertisement

Answer

This is happening because the request url to the server does not contain any query parameters.Change the url written inside the fetch method like this:

Auth.js

    export default {
       verify: (something) => {   //where something is the value of token
         return fetch('/user/verify?token='+something)
           .then(res => res.json())
           .then(data => data);
     }
    }

Also pass the value of something where you are calling it like this:

    AuthService.verify(something).then(data =>{
        const {message} = data;
        setMessage(message);
    });
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement