How to use the request function from axios

Find comprehensive JavaScript axios.request code examples handpicked from public code repositorys.

axios.request is a JavaScript function in the Axios library that sends an HTTP request to a server with configurable options and returns a promise that resolves to the response data.

30
31
32
33
34
35
36
37
38
39

async request(body, headers, config = {}) {
        config.data = body;
        config.headers = headers;
        config = this._checkConfig(config);
        return axios.request(config)
}

async get(url, headers, config = {}) {
        config.headers = headers;
fork icon51
star icon418
watch icon30

21
22
23
24
25
26
27
28
29
30
};

const endpoint = `${appCfg.authUri}?grant_type=${appCfg.authGrantType}`;

try {
    const response = await axios.request({
        url: endpoint,
        method: 'POST',
        headers
    });
fork icon11
star icon17
watch icon3

+ 3 other calls in file

How does axios.request work?

axios.request works by taking a configuration object as its input and returning a promise that resolves to the response data. The configuration object can include various options for the request, such as the request method, URL, headers, data, and timeout, which determine how the request is sent and processed by the server. When called, axios.request first creates a new XMLHttpRequest object or uses the fetch API to send the request to the specified URL, using the specified method and headers, and with the specified data if provided. The response from the server is then processed according to its content type and returned as the result of the promise. If an error occurs during the request or response, axios.request rejects the promise and throws an error with the corresponding status code and error message. Note that axios.request is part of the Axios library, which provides a set of utility functions for making HTTP requests in JavaScript, and supports various request and response formats and interceptors.

17
18
19
20
21
22
23
24
25
26
console.log("Body to send to Okta:")
console.log(formData)
if(formData) {
        try {
                //We're invoking the /token endpoint on Okta- but we're calling the "internal" custom domain URL, behaving as a proxy.
                const oktaResponse = await axios.request({
                        'url': tokenEndpoint,
                        'method': 'post',
                        'headers': {'Content-Type': 'application/x-www-form-urlencoded', 'Host': process.env.BASE_DOMAIN},
                        'data': formData
fork icon9
star icon13
watch icon2

20
21
22
23
24
25
26
27
28
29

options.method = "MKCOL";
options.url = `${process.env.DATABUS_RESOURCE_BASE_URL}/dav/${groupPath}`;

try {
  await axios.request(options);
} catch(err) {
  if(err.response.status != 405) {
    throw(err);
  }
fork icon4
star icon14
watch icon22

+ 2 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const axios = require("axios");

const config = {
  method: "post",
  url: "https://jsonplaceholder.typicode.com/posts",
  headers: {
    "Content-Type": "application/json",
  },
  data: {
    title: "foo",
    body: "bar",
    userId: 1,
  },
};

axios
  .request(config)
  .then((response) => console.log(response.data))
  .catch((error) => console.error(error));

In this example, we first import the axios library and define a configuration object representing an HTTP POST request to the https://jsonplaceholder.typicode.com/posts endpoint, with a Content-Type header of application/json and a JSON object representing a post with a title, body, and user ID. We then use axios.request to send the request and receive the response data as a promise. We then use console.log to print the response data to the console. If the request is successful, the output will be a JSON object representing the new post with an ID generated by the server. If the request fails, the error message will be printed to the console. Note that this is just a simple example, and axios.request can be used to make various types of HTTP requests with different configurations, such as GET, PUT, DELETE, and PATCH requests, and with various response types, such as JSON, XML, or binary data.

115
116
117
118
119
120
121
122
123
124
        path: '/qrs/app/full',
        queryParameters: [{ name: 'filter', value: filter }],
    });
}

const result = await axios.request(axiosConfig);
logger.debug(`GET APP: Result=result.status`);

const apps = JSON.parse(result.data);
logger.verbose(`GET APP: # apps: ${apps.length}`);
fork icon2
star icon7
watch icon2

+ 31 other calls in file

19
20
21
22
23
24
25
26
27
28

console.log("Body to send to Auth0:")
console.log(formData)
if(formData) {
        try {
                const auth0Response = await axios.request({
                        'url': tokenEndpoint,
                        'method': 'post',
                        'headers': {
                                'Content-Type': 'application/x-www-form-urlencoded',
fork icon2
star icon4
watch icon2

94
95
96
97
98
99
100
101
102
103
  headers: {
    
  }
}
//crawling blog main img
axios.request(crawlerOpt).then(function (response) {
  img_url = response.data.split('"yWs4tf" alt=')[1].split('="')[1].split('"')[0];
  /* console.log(img_url); */
}).catch(function (error) {
  console.error(error);
fork icon1
star icon5
watch icon1

+ 2 other calls in file

1
2
3
4
5
6
7
8
9
10

const axios = require('axios');

async function request(url, { method = 'get', ...config } = {}) {
  const auth = { username: 'user', password: process.env.MAILCHIMP_API_KEY };
  return await axios.request({ url, method, auth, ...config });
}

function getUrl(email, suffix) {
  const baseUrl = `https://us10.api.mailchimp.com/3.0/lists/${process.env.MAILCHIMP_AUDIENCE_ID}/members`;
fork icon1
star icon2
watch icon1

45
46
47
48
49
50
51
52
53
54
} else {
  sendData.data = paramsData
}

try {
  const res = await axios.request(sendData)
  return res.data
} catch (err) {
  let errH = err
  if (err.isAxiosError && err.response?.data) {
fork icon1
star icon2
watch icon1

226
227
228
229
230
231
232
233
234
235
236
    })
}


function igdl(url) {
    return new Promise(async (resolve, reject) => {
        axios.request({
            url: 'https://www.instagramsave.com/download-instagram-videos.php',
            method: 'GET',
            headers: {
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
fork icon0
star icon1
watch icon1

+ 15 other calls in file

234
235
236
237
238
239
240
241
242
243

### Request method aliases

For convenience, aliases have been provided for all common request methods.

##### axios.request(config)
##### axios.get(url[, config])
##### axios.delete(url[, config])
##### axios.head(url[, config])
##### axios.options(url[, config])
fork icon0
star icon1
watch icon0

152
153
154
155
156
157
158
159
160
161
if (debug) {
    log(`\n【debug】=============== 这是  请求 url ===============`);
    log(JSON.stringify(options));
}

axios.request(options).then(async function (response) {
    try {
        data = response.data;
        if (debug) {
            log(`\n\n【debug】===============这是 返回data==============`);
fork icon4
star icon0
watch icon1

+ 2 other calls in file

554
555
556
557
558
559
560
561
562
563
} else if (dockerHost._dockerType === "tcp") {
    options.baseURL = DockerHost.patchDockerURL(dockerHost._dockerDaemon);
}

log.debug("monitor", `[${this.name}] Axios Request`);
let res = await axios.request(options);
if (res.data.State.Running) {
    bean.status = UP;
    bean.msg = res.data.State.Status;
} else {
fork icon0
star icon0
watch icon1

+ 5 other calls in file

2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
        8
      ]
    }
  }
};
axios.request(updateUser)
  .then((response) => {
    res.status(200).end();
  })
  .catch((err) => {
fork icon0
star icon0
watch icon1

+ 31 other calls in file

288
289
290
291
292
293
294
295
296
297
let token = a("#token").attr("value");
const param = {
    url: url,
    token: token,
};
const { data } = axios.request("https://downvideo.quora-wiki.com/system/action.php", {
        method: "post",
        data: new URLSearchParams(Object.entries(param)),
        headers: {
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
fork icon0
star icon0
watch icon1

+ 7 other calls in file

884
885
886
887
888
889
890
891
892
893
      "user-agent":
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
    },
  };

  const data = await axios.request(options);
  ALink = data.data.data;
} else {
  console.log("scraper api");
  response = await request(optionsSearch);
fork icon0
star icon0
watch icon1

319
320
321
322
323
324
325
326
327
328
    },
    data: data
};

try {
    const trans = axios.request(config)
        .then((response) => {
            console.log(JSON.stringify(response.data));
        })
        .catch((error) => {
fork icon0
star icon0
watch icon1

195
196
197
198
199
200
201
202
203
204
    'X-RapidAPI-Key': `process.env.X-RapidAPI-Key`,
    'X-RapidAPI-Host': 'bluecart.p.rapidapi.com'
  }
};

return axios.request(options)
  .then(function(response) {
    console.log(response.data)
    // const results = response.autocomplete_results[0].suggestion;
    // console.log('From Walkmart', { results });
fork icon0
star icon0
watch icon2

9
10
11
12
13
14
15
16
17
18
  option: 'GET',
  headers: _headers
};

try {
  const response = await request(options);

  if (response.data) {
    return response.data;
  }
fork icon0
star icon0
watch icon1

+ 2 other calls in file

7
8
9
10
11
12
13
14
15
16
app.use(cors());
app.use(express.json());
app.post("/login", (req,res, next) => {
    const {email, password} = req.body.userData;
    const options = {method: 'GET', url: `http://172.16.70.37/users/${email}&${password}`};
    axios.request(options).then(function (response) {
        if(email === undefined || password === undefined){
            res.status(401).json({
                sucess: false,
                code: 'DD011_API_ERROR_01',
fork icon0
star icon0
watch icon1

+ 3 other calls in file