javascript - axios get 和 post 返回的 data/promise 有区别吗?

标签 javascript reactjs axios

我正在开发一个 React 应用程序,该应用程序使用导入的对象以及对 api 的 get 请求和对相关 API 的 post 请求。

当在 React 前端创建服务的新实例时,我能够成功使用“.then”和“.catch”函数仅从 get 请求访问返回的数据。

当使用来自同一对象的 post 请求时,当尝试访问响应对象时,我得到一个(解释的)“.then”不是未定义的函数。

只有当我在表单提交函数中明确写出发布请求(不使用服务)并处理对象时,我才能检查响应并随后设置状态。

在 React 中使用 axios 的适当/最佳实践方法是什么?为什么当我创建服务的新实例时无法访问响应对象?非常感谢!

服务:

import axios from 'axios';

class ProductServices {
  getAllProducts(){
    return axios.get('https://somecustomAPIURL')
  }

  postProduct(somePathConfig){
    axios.request({
      url: 'https://somecustomAPIURL' + somePathConfig,
      method: 'post',
      headers: {'some-custom-header': process.env.REACT_APP_API_POST_KEY}
    })
  }

}

export default ProductServices;
React Code instantiating and consuming the service (note, that getAllProducts works just fine, but trying to consume a response object in postProduct returns an '.then' is undefined)


  constructor(){
    super();
    this.state = {
      products: [],
      productID: null,
      showModal: false
    }
    this.ProductServices = new ProductServices();
  }

  getAllProducts = () => {
    this.ProductServices.getAllProducts()
    .then((response) => {
      let items = response.data.data.items;
      this.setState({
        products: items,
        productID: items[0].id
      });
      return response;
    })
    .catch((error) => {
      console.log('Error!', error);
      return error;
    })
  }

  handleFormSubmit = (e) => {
    e.preventDefault();
    let productID = this.state.productID;
this.ProductServices.postProduct(productID)
    .then((response) => {
      this.setState({showModal: true}, () => console.log('Success!'));
      return response;
    })
    .catch((err) => {
      console.log('Error!', err);
    })
  }

最佳答案

您在 axios.request 之前错过了 return

import axios from 'axios';

class ProductServices {
...
  postProduct(somePathConfig){
    return axios.request({
      url: 'https://somecustomAPIURL' + somePathConfig,
      method: 'post',
      headers: {'some-custom-header': process.env.REACT_APP_API_POST_KEY}
    })
  }
...

此外,您还可以使用 axios.post 来代替 axios.request,例如 axios.get

return axios.post(url, body, { headers });
return axios.get(url, { headers });
return axios.put(url, body, { headers });
return axios.delete(url, { headers });
return axios.request(axiosConfigOptions);

关于javascript - axios get 和 post 返回的 data/promise 有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58225934/

相关文章:

javascript - 使用 VueX Store 中的计算属性进行 Ajax 调用的正确方法是什么

javascript - getUserMedia() 音频 - POST 到网络服务器?

javascript - 使用 axios 将图像发送到 Node.js,然后进一步使用它

Javascript 将 URL 转换为 BASE64 图像

javascript - 根据视口(viewport)宽度 react js设置初始常量

python - 使用 Reactjs 和 Flask 上传文件

外部文件中javascript中的Javascript reactJs css

javascript - 如何使用 http 请求将 Vue 表单输入发送到 Adonis Controller

c# - 使用 Controller 返回的值填充图表

javascript - 如何处理ext.net中打印网格面板的方向