axios获取请求参数

Axios get request parameters

嗨,我正在做一个 axios 请求来获取图像,但是响应参数不能分配给任何类型的变量,但我可以在 console.log 中读取它们我哪里错了?

 let string = null;

        axios.get('/images/0dace5ee-1be7-4d2c-a07fb03927096815')
            .then(res =>{
                 console.log(res.data) //returns the value of the binary
                 console.log(res.headers['content-type']);//returns the current type image/png
                 string = 'data:'+res.headers['content-type']+';base64,'+ btoa(res.data);
        })
        .catch(error => {
            console.log(error)
        })
        console.log(string)//returns null

console.log(字符串);应该在承诺链内。

更多关于promises

因为他们 运行 异步,您的 console.log (在 then 链之外)将 运行 在承诺完成之前。因此,调用后需要 运行 的所有工作都必须在 .then 链中。或 .catch 错误

let string = null;

        axios.get('/images/0dace5ee-1be7-4d2c-a07fb03927096815')
            .then(res =>{
                 console.log(res.data) //returns the value of the binary
                 console.log(res.headers['content-type']);//returns the current type image/png
                 string = 'data:'+res.headers['content-type']+';base64,'+ btoa(res.data);
                 // it's async so you should console.log in in .then promise chain.
                 console.log(string);             
        })
        .catch(error => {
            console.log(error)
        })