如何在post axios response php next.js中获取数据?

h4cxqtbf  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(153)

这是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

ktecyv1j

ktecyv1j1#

我很确定你在这里跳过了一个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用引号将数据括起来,表示数据的类型为string。
看看Res.request.data,它周围没有引号。它看起来像一个物体。猜测axios已经在值上调用了JSON.parse。
由于Res.request.responseRes.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]

如果还是不行,告诉我。

相关问题