Home > front end >  Pass URL as a parameter in an axios request function
Pass URL as a parameter in an axios request function

Time:12-21

How can I pass a url as a parameter in an axios Post Request function? I am currently defining the url in functions.js. But what I want is to pass it as a parameter and define it in my index.js, or have anyone who is using the function define their own BASEURL depending on their deployment. How can I achieve this?

functions.js

const axios = require("axios");
const BASE_URL = "http://localhost:1800";
const postData = async (body) => {
  try {
    const headers = {
      "DATA-API-Version": "v2",
    };
    const response = await axios.post(`${BASE_URL}/data`, body, {
      headers,
    });
    console.log(response);
    if (response.status === 200) {
      return response;
    }
  } catch (error) {
    console.error(error);
  }
};

index.js

const express = require("express");
const functions = require("./functions.js");
const BASE_URL = "http://localhost:1800";

const payload = require("./test.json");
const app = express();
const PORT = 3000;
app.use(express.json());
app.listen(PORT, () => {
  console.log(`Running this application on the PORT ${PORT}`);
});

const sendData = async (req, res, next) => {
  try {
    const body = payload;
    const response = await functions.postData(body);
    if (response.status === 200) {
      res.send(response.data);
    }
  } catch (err) {
    console.error(err);
  }
};

CodePudding user response:

You can use axios.create to make a new instance of axios with some configuration options already set. Then, perform all operations using that instance.

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

CodePudding user response:

If you want consumers of postData to be able to set their own base URL, then allow them to pass it in as a parameter.

You could even make it optional and provide a default value

const axios = require("axios");
const DEFAULT_BASE_URL = "http://localhost:1800";
const headers = {
  "DATA-API-Version": "v2",
};

const postData = async (body, baseURL = DEFAULT_BASE_URL) => {
  try {
    return (
      await axios.post("/data", body, {
        baseURL,
        headers,
      })
    ).data;
  } catch (error) {
    console.error(error.response?.data, error.toJSON());
    throw new Error("postData failed");
  }
};

Then your consumers can use either

res.send(await functions.postData(payload));

or

res.send(await functions.postData(payload, "https://example.com"));
  • Related