使用Redux从REACT调用API时的路由问题



我用Python创建了api (django restframework)。我正在使用redux从我的react应用程序调用该api。

当我像这样调用它时,它可以正常工作

const {data} = await axios.get(`http://127.0.0.1:8000/api/products/${id}`)

但是当我把url改成

const {data} = await axios.get(`api/products/${id}`)

然后向另一个路由(http://localhost:3000/product/api/products/6)发出请求,我希望它呼叫(http://localhost:8000/api/products/6

)我已经在django服务器中添加了路径,并允许从react应用程序调用。当我与其他路由一起工作时,它工作得很好。

例如,当我调用这个路由

时,它工作得很好
const {data} = await axios.get('api/products/')

你需要给api url。如果你不提供完整的url,它会添加你的react应用的url。

你可以用路由

声明一个变量
API_URL = "http://localhost:8000/"
const {data} = await axios.get(`${API_URL}api/products/${id}`)
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
},
},
},
};

将上述配置添加到你的webpack中,那么请求就可以由wepack开发服务器转发了。

详情请浏览https://webpack.js.org/configuration/dev-server/#devserverproxy

最新更新