从 axios 获取和发布返回的数据/承诺是否有差异?



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

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

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

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

在 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);

最新更新