'Axios: returns 404 when making POST request

I am new with nodejs and axios. I am working on making the login work as of the moment, but Axios is giving me a 404 not found error whenever I call it inside my controller.

This is how I am doing it. I'm pretty sure I am using axios correctly. I don't have any idea as to why it is giving 404 error.

app.post('/post-login', urlencodeParser, async function (req, res) {
    const instance = axios.create();
    req.body.grant_type = "password";
    req.body.client_id = null;
    req.body.client_secret = null;
    
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    }

    try{
      const response = await instance.post(jsonData.baseURL+'/auth/login',JSON.stringify(req.body),{headers:headers});
      res.status(200).json(response);
      console.log(response);
    }catch(e){
      res.status(500).json({ message: e });
    }
});

UPDATE:

this is what I get when testing the API endpoint in postman postman data

and this is the headers headers



Solution 1:[1]

I think the problem might be that you're using json encoded data (by using json.stringify) and sending it using the 'application/x-www-form-urlencoded' content type. I would advise you to pass the body without encoding it. Like this:

app.post('/post-login', urlencodeParser, async function (req, res) {
    const instance = axios.create();
    req.body.grant_type = "password";
    req.body.client_id = null;
    req.body.client_secret = null;
    
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    }

    try{
      const response = await instance.post(jsonData.baseURL+'/auth/login', req.body,{headers:headers});
      res.status(200).json(response);
      console.log(response);
    }catch(e){
      res.status(500).json({ message: e });
    }
});

More on why you should not pass an encoded json to axis with form content-type

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jeremynac