这是axios的帖子响应我试图在帖子axios的响应中获得错误的文本我从(Res.request.response(它在对象中给出对象当我添加.data
时,它变成了undefined
。
{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {url: "https/v1/user/login", method: "post", data: "{"email":"09@gmail.com","password":"it"}", headers: {…}, transformRequest: Array(1), …}
data: {success: true, statusCode: 200, data: {…}}
headers: {access-control-allow-headers: "x-requested-with, Content-Type, origin, authorization, accept, client-security-token", access-control-allow-methods: "POST, GET, OPTIONS, DELETE, PUT", access-control-allow-origin: "*", access-control-max-age: "1000", connection: "keep-alive", …}
request: XMLHttpRequest
onabort: ƒ ()
onerror: ƒ ()
onload: null
onloadend: null
onloadstart: null
onprogress: null
onreadystatechange: ƒ ()
ontimeout: ƒ ()
readyState: 4
response: "{"success":true,"statusCode":200,"data":{"errors":{"password":["Incorrect email or password"]}}}"
responseText: "{"success":true,"statusCode":200,"data":{"errors":{"password":["Incorrect email or password"]}}}"
responseType: ""
responseURL: "https://cors-anywhere.herokuapp.com/https://api.w.com/v1/user/login"
responseXML: null
status: 200
statusText: "OK"
timeout: 0
upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}
withCredentials: false
__proto__: XMLHttpRequest
status: 200
statusText: "OK"
当我尝试console.log(Res.request.response(时这是的结果
{"success":true,"statusCode":200,"data":{"errors":{"password":["Incorrect email or password"]}}}
我如何迭代得到这个结果:Incorrect email or password
很确定您正在跳过此处的data
。
尝试Res.request.response.data.data.errors.password.join('n')
join('\n'(是可选的。您可以将其替换为...password[0]
。
如果你想学习一点,这就是我探索这个物体的方法。这本身就是一种技能。
让我们试一试。
根据您在上面打印的内容(Res.request.response
(,我做了以下操作:
let respData = JSON.parse('{"success":true,"statusCode":200,"data":{"errors":{"password":["Incorrect email or password"]}}}');
console.log(respData.data.errors.password.join('n'));
// logs: "Incorrect email or password"
奏效了。
请注意,console.log用引号将数据括起来,表示数据的类型字符串。
看看Res.request.data
,它周围没有引号。它看起来像一个对象。猜测axios已经对该值调用了JSON.parse。
由于Res.request.response
和Res.request.data
在对象中处于同一级别,因此看起来Res.request.data === {success: true, statusCode: 200, data: {…}}
。
要获取您想要的数据,您需要调用Res.request.data.data
来访问响应的这一部分。
换句话说:
let responseData = Res.request.data;
responseData.success === true
let errors = responseData.data.errors
let firstPasswordError = errors.password[0]
如果没有帮助,请告诉我。