Home > Enterprise >  How to call REST API inside node js with relative url?
How to call REST API inside node js with relative url?

Time:01-31

I have code in my express controller like this :

const http = require('axios');

module.exports = {
    login: (req, res) => {
        res.render("admin/login.ejs", { errorMessage: req.flash('message')[0] });
    },
    processLogin: (req, res) => {
        axios.post(`/api/login`, {
                "email": req.body.email,
                "password": req.body.password
            })
            .then(function(response) {
                console.log(response);
            })
            .catch(function(error) {
                console.error(error);
            });
    }
}

This path "/api/login" API url is defined in express route in same application. But, it gives me me error like this :

TypeError [ERR_INVALID_URL]: Invalid URL
    at new NodeError (node:internal/errors:372:5)
    at URL.onParseError (node:internal/url:553:9)
    at new URL (node:internal/url:629:5)
    at dispatchHttpRequest (D:\projects\calvarycomz.com\node_modules\axios\dist\node\axios.cjs:2394:20)    
    at new Promise (<anonymous>)
    at http (D:\projects\calvarycomz.com\node_modules\axios\dist\node\axios.cjs:2330:10)
    at Axios.dispatchRequest (D:\projects\calvarycomz.com\node_modules\axios\dist\node\axios.cjs:3260:10)  
    at Axios.request (D:\projects\calvarycomz.com\node_modules\axios\dist\node\axios.cjs:3610:33)
    at Axios.httpMethod [as post] (D:\projects\calvarycomz.com\node_modules\axios\dist\node\axios.cjs:3649:19)
    at Function.wrap [as post] (D:\projects\calvarycomz.com\node_modules\axios\dist\node\axios.cjs:27:15) {  input: '/api/login',
  code: 'ERR_INVALID_URL'
}

I know the error occurs because the prefix hostname (http://localhost:30000) is not included in the axios endpoint. How can I make an http request using axios just including the url path?

CodePudding user response:

Try to create an axios instance and specify the baseUrl for it.
You should then be able to specify only the paths for your requests with:

const axios = require('axios');

const axiosInstance = axios.create({
  baseUrl: 'http://localhost:3000'
})

module.exports = {
  login: (req, res) => {
    res.render('admin/login.ejs', { errorMessage: req.flash('message')[0] });
  },
  processLogin: (req, res) => {
    axiosInstance
      .post(`/api/login`, {
        email: req.body.email,
        password: req.body.password,
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.error(error);
      });
  },
};

CodePudding user response:

Try using the baseURL property of axios instance to set the hostname for all requests you make through it.

This should work:

const axios = require('axios').default;
const instance = axios.create({
    baseURL: 'http://localhost:30000'
});

module.exports = {
    login: (req, res) => {
        res.render("admin/login.ejs", { errorMessage: req.flash('message')[0] });
    },
    processLogin: (req, res) => {
        instance.post(/api/login, {
            "email": req.body.email,
            "password": req.body.password
        })
        .then(function(response) {
            console.log(response);
        })
        .catch(function(error) {
            console.error(error);
        });
    }
}

Replace http://localhost:30000 with the correct hostname for your application.

CodePudding user response:

To make an HTTP request using Axios, you need to include the full URL including the hostname. You can define the hostname in a constant and use it in all Axios requests, e.g.:

const axios = require('axios');
const baseURL = 'http://localhost:30000';

module.exports = {
processLogin: (req, res) => {
axios.post(${baseURL}/api/login, {
"email": req.body.email,
"password": req.body.password
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.error(error);
});
}
}
  • Related