我试图了解如何在函数中使用 axios ( https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.0/axios.js ) 与我自己的后端对话以获取一些数据。
下面的代码有效。
我需要在函数外定义一个全局变量来捕获结果。
如果我将变量 myresponse 移动到函数中,我将无法再接收到回复。
如何避免全局变量?
var myresponse = "xxx"
function getTimeData() {
axios.get('/time')
.then(function (response) {
console.log(response.data);
myresponse = response.data;
})
.catch(function (error) {
myresponse = "error";
});
return myresponse;
}
console.log(getTimeData())
对于这个例子,我在“/time”运行一个本地服务器,它返回一个时间字符串。
最佳答案
全局变量可以在axios内部使用。由于 axios 使用 AJAX,因此您不应在 axios 外部返回。
var myresponse = "xxx"
function getTimeData() {
axios.get('/time')
.then(function (response) {
myresponse = response.data;
return myresponse;
})
.catch(function (error) {
myresponse = "error";
return myresponse;
});
}
console.log(getTimeData())
这会起作用。 即使在您的代码中,在记录 myresponse 时也不会设置,但在收到响应后,它将设置为 response.data。
我的 vue 代码的一部分工作正常。请注意,创建后 this.users 不会立即获取 res.data 中的值,但一旦 axios 发送请求并接收到它,它将包含 res.data。
var HTTP = axios.create({
baseURL: URL,
})
methods:{
getUsers(){
return HTTP.get('/users/admin')
},
deleteUsers(user){
HTTP.post('/users/admin',{
id : user._id
})
.then(()=>{
this.getUsers()
})
}
},
created(){
this.getUsers().then(res=>{
this.users = res.data;
})
}
关于javascript - 在没有全局变量的javascript函数中使用axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49340469/