这是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.wodworx.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
答案 0 :(得分:0)
很确定您在这里跳过了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]
如果那没有帮助,请告诉我。