新的 axios 请求作为响应
New axios request in response
我正在使用 axios 发布到 API,并使用响应中的数据我想发出另一个 API 请求,但我 运行 遇到了问题说axios is not defined
.
我的 Vue 登录组件中的调用如下:
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
this.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
正如我之前提到的,我的控制台中的错误如下:TypeError: Cannot read property 'axios' of undefined
。
我试过在没有 this.
的情况下编写第二个请求,但我遇到了同样的问题。我哪里错了?
你必须在这里使用 arrow function。
常规函数有自己的 this
值。
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
this.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
或者如果您更喜欢老式的方式,您可以保存 this
对某些变量的引用以便在回调中访问它:
const self = this
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
self.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
我正在使用 axios 发布到 API,并使用响应中的数据我想发出另一个 API 请求,但我 运行 遇到了问题说axios is not defined
.
我的 Vue 登录组件中的调用如下:
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
this.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
正如我之前提到的,我的控制台中的错误如下:TypeError: Cannot read property 'axios' of undefined
。
我试过在没有 this.
的情况下编写第二个请求,但我遇到了同样的问题。我哪里错了?
你必须在这里使用 arrow function。
常规函数有自己的 this
值。
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
this.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})
或者如果您更喜欢老式的方式,您可以保存 this
对某些变量的引用以便在回调中访问它:
const self = this
this.axios({
method: 'post',
url: '/my_api/test',
data: "testdata=test123",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
self.axios({
method: 'get',
url: '/my_api/test2',
data: "testdata2=" + response.data.id
})
})