【问题标题】:Return the Response got from fetch/Axios API with POST method - Node JS使用 POST 方法返回从 fetch/Axios API 获得的响应 - Node JS
【发布时间】: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


【解决方案1】:

试试这个:

resp = await fetch('URL',requestOptions)
      .then(res) => {
        console.log(res)
      })
      .catch(e=>{
        console.log(e)
      });

用 axios

    try{
let resp = await axios.post(URL ,options)
        console.log('---------'+resp+'----------') //i am not getting any response here
        return resp;
}
catch(e){
console.log(e)
}

【讨论】:

  • 嗨,Abhishek,上面发布的变体没有用,Axios 代码在对象中返回具有零列表值的响应。在哪里获取它给我一个错误。你可以看看并编辑它。
  • 这是您的后端代码的问题,请查看错误以获取更多信息
  • 感谢您的回复,只是我必须使用查询字符串对表单数据进行字符串化
猜你喜欢
  • 2019-10-03
  • 1970-01-01
  • 2020-04-22
  • 2022-01-08
  • 2020-04-28
  • 2021-07-18
  • 2018-11-26
  • 2022-08-05
  • 1970-01-01
相关资源
最近更新 更多