Home > Enterprise >  Routing Problem in calling API from REACT using Redux
Routing Problem in calling API from REACT using Redux

Time:05-30

I have create api with Python (django restframework). I am calling that api from my react applicaation using redux.

It works fine when i call it like this

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

but when i change the url to

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

It then makes a request to a different route ( http://localhost:3000/product/api/products/6) and I want it to make a call to (http://localhost:8000/api/products/6

I have added the path in django server and allowed calls from the react app. and it is working perfectly when i was working with other routes.

for example it was working fine when i was making call to this route

const {data} = await axios.get('api/products/')

CodePudding user response:

You need to give the url to the api. If you don't provide full url, it will add your react app url.

You can declare a variable with the route

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

CodePudding user response:

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': {
         target: 'http://127.0.0.1:8000',
         changeOrigin: true,
      },
    },
  },
 };

Add the above configuration to your webpack,then the request can be forwarded by wepack dev server.

more details,please visit https://webpack.js.org/configuration/dev-server/#devserverproxy

  • Related