所以我的后端开发人员给了我一个端点来测试prefill
表单数据。
所以它是GET
请求http://localhost:3000/v0/in_progress_forms/MDOT
并且我在POSTMAN中传递键/值对test:test
并且我得到以下答复:
{
"form_data": {
"profileFullName": {
"first": "Greg",
"middle": "A",
"last": "Anderson"
},
"gender": "M",
"profileAddress": {
"street": "ADDY 3",
"city": "Detroit",
"state": "MI",
"country": "USA",
"postalCode": "22312"
},
"email": "[email protected]",
"dateOfBirth": "1933-04-05"
},
"metadata": {
"version": 0,
"prefill": true,
"returnUrl": "/profile-information"
}
}
因此,我在React中设置了我的api请求:
export const getUserInformation = formData =>
apiRequest(`v0/in_progress_forms/MDOT`, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
body: JSON.stringify(formData),
});
然后我只是尝试在我的react组件中对其进行测试
import React from 'react';
import { getUserInformation } from './api';
class MyComponent extends React.Component {
componentDidMount() {
getUserInformation().then(data => {
if (data.error) {
console.log(data.error);
} else {
console.log(data);
}
});
}
render() {
return (
<div>
My Component
</div>
);
}
}
export default MyComponent;
因此,当我进入控制台时,会看到以下响应:
Response {type: "basic", url: "http://localhost:3001/mdt/2346/v0/in_progress_forms/MDOT", redirected: false, status: 200, ok: true, …}
type: "basic"
url: "http://localhost:3001/mdt/2346/v0/in_progress_forms/MDOT"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers
__proto__: Headers
body: (...)
bodyUsed: false
__proto__: Response
但是我没有从POSTMAN获得数据。如何构造该结构以查看数据。
这里需要记住,您正在处理response
对象。响应对象将包含一些有关其结果的元数据。例如HTTP状态代码,URL等...如果要获取响应数据,只需访问响应主体:
getUserInformation().then(data => {
if (data.error) {
console.log(data.error);
} else {
//access the response body
console.log(data.body);
}
});
我不知道您正在使用什么来发送请求,但是如果您使用的是提取API,则需要先使用json()
解析数据,这是另一个承诺,然后将其用作数据
getUserInformation().then((response) => {
response.json().then((data) => {
console.log(data);
});
});
FYI,axios是针对浏览器和node.js的基于Promise的流行HTTP客户端库,已经为您自动转换了请求和响应数据。