Search code examples
javascriptnode.jsreactjsexpressreact-fullstack

React + Expressjs URL params returning undefined on get request


so I'm trying to make a web application that stores the user. I want to use this user in the back-end to retrieve information. So right now a button is clicked and that calls the back-end, the onClick function currently looks like this.

const getBackend = () => {
    let url = new URL('https://http://localhost:4000/backend');
    url.search = new URLSearchParams({
        username: user,
    });
    fetch(`http://localhost:4000/prize`, {
        method: "GET",
        url:url,
    });
}

and my express.js server looks like this:

app.get("/backend", async (req, res) => {
    let user = req.query.username;
    console.log("user");
    res.send(user);
}

What happens is that when I click the button from the front end with the getBackend function the console and browser will log the user as "undefined". However, when I put the link on the browser directly as: http://localhost:4000/prize?username=test3%40something.edu I successfully get "test3@something.edu" working. How can I make the button give me the same as putting it on the browser?

Thank you.


Solution

  • I think you accidently added the https in the url. You should leave off the https and just keep the http

    const getBackend = () => {
        let url = new URL('http://localhost:4000/backend');
        url.search = new URLSearchParams({
            username: user,
        });
        fetch(`http://localhost:4000/prize`, {
            method: "GET",
            url:url,
        });
    }