获取方法 POST - 响应数据是 Promise pending
Fetch method POST - response data is Promise pending
我有一个组件 fetch method='POST'
它的功能之一:
handleSubmit(context) {
let json = {
username: this.state.username,
password: this.state.password,
}
json = JSON.stringify(json)
fetch(`/api/auth/token/`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: json,
})
.then(response => response.json())
.then(response => this.loginSuccess(context, response))
}
这是 loginSuccess
函数:
loginSuccess(context, response) {
console.log('Login Success!')
context.toggleLoginModal()
context.toggleLoggedIn()
context.setUsername(response.profile_username)
context.setUserId(response.profile_id)
}
此代码的问题是,如果响应不在 200 到 300 之间,如 错误请求 ,loginSuccess
中的所有代码仍将被处决,这是不应该发生的。
所以,我变了
.then(response => response.json())
.then(response => this.loginSuccess(context, response))
至:
.then(response => {
response.status >= 200 && response.status < 300 ?
this.loginSuccess(context, response.json())
:
console.log(response)
})
现在,在 loginSuccess
方法中,参数 response
是 Promise {<pending>}
而 response.profile_username
是 undefined
。
如何解决这个问题?
承诺尚未实现。尝试类似的东西:
.then(response => {
response.ok ?
response.json().then(json => { this.loginSuccess(context, json) })
:
console.log(response)
})
我有一个组件 fetch method='POST'
它的功能之一:
handleSubmit(context) {
let json = {
username: this.state.username,
password: this.state.password,
}
json = JSON.stringify(json)
fetch(`/api/auth/token/`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: json,
})
.then(response => response.json())
.then(response => this.loginSuccess(context, response))
}
这是 loginSuccess
函数:
loginSuccess(context, response) {
console.log('Login Success!')
context.toggleLoginModal()
context.toggleLoggedIn()
context.setUsername(response.profile_username)
context.setUserId(response.profile_id)
}
此代码的问题是,如果响应不在 200 到 300 之间,如 错误请求 ,loginSuccess
中的所有代码仍将被处决,这是不应该发生的。
所以,我变了
.then(response => response.json())
.then(response => this.loginSuccess(context, response))
至:
.then(response => {
response.status >= 200 && response.status < 300 ?
this.loginSuccess(context, response.json())
:
console.log(response)
})
现在,在 loginSuccess
方法中,参数 response
是 Promise {<pending>}
而 response.profile_username
是 undefined
。
如何解决这个问题?
承诺尚未实现。尝试类似的东西:
.then(response => {
response.ok ?
response.json().then(json => { this.loginSuccess(context, json) })
:
console.log(response)
})