这是axios post response我试图在post axios的响应中获取错误的文本我从(Res.request.response)开始它给予对象中的对象中的对象当我去添加.data
时它变成了undefined
。
{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config: {url: "https/v1/user/login", method: "post", data: "{"email":"[email protected]","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
1条答案
按热度按时间ktecyv1j1#
我很确定你在这里跳过了一个
data
。试试
Res.request.response.data.data.errors.password.join('\n')
.join('\n')是可选的。可以用
...password[0]
替换。如果你想学一点,这就是我探索这个物体的方法。这本身就是一种技能。
让我们给予它一个镜头。
根据上面打印的内容(
Res.request.response
),我做了以下操作:这招奏效了
请注意,console.log用引号将数据括起来,表示数据的类型为string。
看看
Res.request.data
,它周围没有引号。它看起来像一个物体。猜测axios已经在值上调用了JSON.parse。由于
Res.request.response
和Res.request.data
在物体中处于同一水平,因此看起来Res.request.data === {success: true, statusCode: 200, data: {…}}
。要获取所需的数据,需要调用
Res.request.data.data
来访问响应的这一部分。换句话说:
如果还是不行,告诉我。