我有一个/services/userService.js文件在next 3:
const baseURL = 'http://localhost:8080/api/auth/'
const headers = {
Accept: 'application/json',
'Content-type': 'application/json',
}
export default {
signinNewUser(firstName, secondName, email, password) {
return useFetch('/signup', {
method: 'POST',
baseURL: baseURL,
headers: headers,
body: {
firstName,
secondName,
email,
password,
},
})
},
}
我在/store/user.js中有以下函数
async registerUser(firstName, secondName, email, password) {
return userService
.signinNewUser(firstName, secondName, email, password)
.then(
(res) => {
const data = res.data.value
const error = res.error.value
if (error) {
console.log(error)
} else {
this.registered = true
}
},
(error) => {
console.log('exception...')
console.log(error)
}
)
},
我的认证API可以在响应体中使用400状态码和不同的错误消息来回答,例如:
{"message":"Error: Email is already in use!"}
{"message":"Error: FirstName is already in use!"}
等等……
我希望能够访问这些消息,以便向用户显示不同的错误消息,以便他/她知道如何解决问题。
我怎么才能做到呢?
我尝试访问错误对象,但它不包含对响应体的引用,数据对象为空
您可以使用错误引用对象中的data
键访问错误响应的主体。http错误不会总是在可组合文件中引发错误。
const data = error.value.data;
async registerUser(firstName, secondName, email, password) {
return userService
.signinNewUser(firstName, secondName, email, password)
.then(
(res) => {
const data = res.data.value
const error = res.error.value
if (error) {
console.log(error)
this.error = error.data; // <== To handle the error data.
} else {
this.registered = true
}
},
(error) => {
console.log('exception...')
console.log(error)
}
)
},
此外,useFetch
可组合允许您使用interceptors
以另一种方式访问数据,请参阅有关该主题的文档。