【发布时间】:2020-07-18 03:56:57
【问题描述】:
我想知道如何使用fetch返回POST方法API的数据
- 我的 API 包含一个带有 2 个参数的表单数据
- 我尝试使用 Axios,我没有得到数据来显示或返回响应
- 当我尝试使用 Fetch 时,我能够获得响应,但无法将数据返回到另一个 JS 文件。
使用抓取:
method: 'POST',
body: formdata,
redirect: 'follow'
};
let resp = await fetch('URL',requestOptions)
.then(res => Promise.all([res.status, res.json()]))
.then(([status, jsonData]) => {
console.log('jsonData : ', jsonData); // here i am getting the response
console.log('status : ', status);
console.log('resp : ', resp); //here i am getting as UNDEFINED
return resp;
});
使用 Axios:
let options = {
'headers': {
},
formData: {
'para1': '';
'para2': '';
}
};
let resp = await axios.post(URL ,options)
console.log('---------'+resp+'----------') //i am not getting any response here
return resp;
即使有 request 我也能够从 api 获得响应,但无法将其返回到另一个 JS 文件。
提前谢谢你。
【问题讨论】:
-
您将在决赛中返回
resp变量,但这是不正确的。您应该立即将其返回到当前位置下方的两行,即在决赛之外。您立即返回并使用承诺,而不是在最终解决时! -
嗨@GeorgiB.Nikolov,我没听懂..可以将它作为你的解释的答案发布或在这里简要解释。
标签: javascript node.js api post axios