Search code examples
javascriptnode.jsapiserver

How to access data from API Payload


I am making an api call like this
axios.get("http://localhost:4000/loginUser", { email: enteredEmail, password: enteredPass})
now i want in the server code to access these email and password fields given to the API call,

app.get("/loginUser", async (req, res) => {
   try {
        email = // don't know how to access this email field from **req**
   } catch (error) {
         res.status(400).send("invalid credentials");
   }
});

i tried accesssing it from res.body but it is empty as i am passing the data as payload. and tried passing as params but the @ symbol in email is giving issues.


Solution

  • From the documentation:

    axios.get(url[, config])
    

    The second argument to get is the configuration not the request body.

    GET requests can't have bodies.

    If you want to encode data in a GET request, you can do it in the URL (do not do this for passwords).

    const url = new URL("http://localhost:4000/loginUser");
    url.searchParams.set("email", enteredEmail);
    url.searchParams.set("password", enteredPass);
    axios.get(url);
    

    where it will be accessible in Express via the query property.


    If you want to pass credentials do not use the URL. Requested URLs tend to be logged in clear text by web servers.

    Make a POST request instead.