Home > front end >  Is react-router messing with the API Url?
Is react-router messing with the API Url?

Time:10-17

I have a API that works fine, but when i use it with react, the get request goes to

/api/profile/posts/profile/matt

whereas it should go to:

/api/posts/profile/matt

The proxy is set on localhost:8000/api, that works fine for the other APIs when is working with react.

Code for calling the APIs(Only profile one doesn't work, rest all work fine, even the profile one works when I use the absolute URL):

const res = username 
            ? await axios.get("posts/profile/" username)
            : await axios.get("posts/timeline/6120b0e07ea0361eb4982b1c");

code for routes:

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/">
          <Home />
        </Route>
        <Route path="/login">
          <Login />
        </Route>
        <Route path="/register">
          <Register />
        </Route>
        <Route path="/profile/:username">
          <Profile />
        </Route>
      </Switch>
    </Router>
  )
}

I have similar problem with this user as well: How to prevent React-router from messing up your API url

CodePudding user response:

when you call an API, you need to pass a full path URL to the fetch or axios to work properly, but there are some points that need to be mentioned.

All APIs have two parts: a base URL (which is not changing) other parts

For example: https://someAddress.com/api/posts/profile/matt

The base URL is https://someAddress.com/api/ here.

The Axios take a baseURL parameter to call your API's without specifying on every API call:

axios.defaults.baseURL = 'https://somwAddress.com/api/;

Now, simply call your API:

axios.get("posts/profile/"   username)

It requests to the full URL: https://someAddress.com/api/posts/profile/username

CodePudding user response:

You should provide the full URL in axios.get() method. for example- "HTTP://localhost:port/api_path".

Why only profile API messing with you because you have a profile route mentioned in your router

    <Route path="/profile/:username">
        <Profile />
    </Route>

You are not using any wild card routes if you would have It would create problem with every api

  • Related