简体   繁体   English

获取API POST请求响应

[英]fetch API POST request response

I am trying to get output from the post request once the form has been submitted but I get a promise response rather than the actual data when posting the form 表单提交后,我试图从发布请求中获取输出,但是发布表单时我得到了一个Promise响应而不是实际数据

fetch('localhost/clients', {
  method: 'post',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(formData)
}).then(response => {
  console.info('Sending Message ...')
  console.info(response.json())
}).catch (error => {
  console.log(error)
})

The data gets passed to the backend however I want to return the data thats been outputted by the API server. 数据被传递到后端,但是我想返回API服务器输出的数据。

response.json() returns a Promise. response.json()返回一个Promise。 You need to use it like below. 您需要像下面一样使用它。

fetch('localhost/clients', {
  method: 'post',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(formData)
}).then(response => {
  return response.json();
}).then(jsonResponse => {
  console.log(jsonResponse);
}).catch (error => {
  console.log(error)
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM