【问题标题】:How to get/post with axios?如何使用 axios 获取/发布?
【发布时间】:2018-10-13 10:35:19
【问题描述】:

我想用 axios 发出一个 get 和一个 post 请求(应该是异步的)。

代码如下:

async getJSONAsync()
    {
       await app.get('https://*****.io/index.php?/api/v2/get_case/5892', {
            headers: {'Content-Type' : 'application/json'},
            auth: {
                username : '************',
                password : '*********************'
            }
        }).then(function (response) {
            console.log(response);
        })
            .catch(function (error) {
                console.log(error);
            });
    }

问题是 - 我应该如何存储 baseURL 和其他选项,如标头、身份验证信息、正文(数据)以及当我返回结果时 - 如何将它与另一个函数一起使用 - 比如发布带有来自先前获取请求的一些数据回复? 我在这里迷路了。请帮忙。

【问题讨论】:

  • "我应该如何存储 baseURL 和其他选项,如 headers、auth info、body(data)" — Axios 文档有问题吗?
  • "like post with some data from previous get request response" — 与任何其他函数完全相同。更改 getJSONAsync() 使其接受参数。
  • 在深入了解使用 Promise 的复杂库之前,您可能应该先完成介绍性的 JavaScript 教程。
  • 我是 javascript 新手。我是否应该创建带有选项的单独 js 文件,然后将其传递给该函数?它应该是什么样子?

标签: javascript async-await axios ecmascript-2017


【解决方案1】:

const axios = require('axios');


const getRandomDogPicture = async () => {
    const instance = axios.create({
        baseURL: "https://dog.ceo/api/breeds/image/random",
        timeout: 1000,
        headers: {
            'X-Custom-Header': 'foobar'
        }
    });

    let result = await instance.get().then(result => result.data);
    return result;
}

const func = async () => {
    let ans = await getRandomDogPicture();
    console.log(ans)
}
console.log(func());

【讨论】:

  • 在哪里添加授权,content-type header?
  • @LittleJohnny ?
猜你喜欢
  • 2020-06-20
  • 1970-01-01
  • 2021-11-26
  • 2017-12-05
  • 1970-01-01
  • 2018-08-31
  • 1970-01-01
  • 2018-12-25
  • 2019-04-29
相关资源
最近更新 更多