I have the proxy set as http://localhost:8000/api (works fine for other requests)
In react I'm using axios for a get request:
const res = username
? await axios.get("posts/profile/" username)
: await axios.get("posts/timeline/6120b0e07ea0361eb4982b1c");
when the username is not defined the second condition works, but when the username is provided, the first condition sends request to another url: in VSCode Terminal where backend is running this is visible:
::ffff:127.0.0.1 - - [15/Oct/2021:15:38:12 0000] "GET /api/profile/posts/profile/matt HTTP/1.1" 404 169
It should go to /api/posts/profile/matt but instead it goes to the above one
In chrome console:
xhr.js:210 GET http://localhost:3000/profile/posts/profile/matt 404 (Not Found)
In POSTMAN the api works. When I use the full URL in like:
const res = username
? await axios.get("http://localhost:8000/posts/profile/" username)
: await axios.get("posts/timeline/6120b0e07ea0361eb4982b1c");
After using the full url the app works fine, but it should work properly when without the full URL as I have already set the proxy and it works fine for other get requests, even the timeline one works well without the full url.
Here is the code for react 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>
)
}
and here are the APIs(they work fine when used with correct URL):
//GET TIMELINE POSTS
router.get("/timeline/:userId", async (req, res) => {
try {
const currentUser = await User.findById(req.params.userId);
const userPosts = await Post.find({ userId: currentUser._id });
const friendPosts = await Promise.all(
currentUser.following.map( friendId => {
return Post.find({ userId: friendId });
})
);
res.status(200).json(userPosts.concat(...friendPosts));
} catch( err ) {
res.status(500).json(err);
}
});
//GET User's all POSTS
router.get("/profile/:username", async (req, res) => {
try {
const user = await User.findOne({username: req.params.username});
const posts = await Post.find({userId: user._id});
res.status(200).json(posts);
} catch( err ) {
res.status(500).json(err);
}
});
What can be the issue here? The problem is only happening with the profile request(sends request to wrong url)
CodePudding user response:
Your relative URL is resolved differently than you think. You could debug this, but I would recommend just using absolute URLs to ensure you know how they resolve:
const res = username
? await axios.get("/api/posts/profile/" username)
: await axios.get("/api/posts/timeline/6120b0e07ea0361eb4982b1c");
CodePudding user response:
adding a slash before posts worked:
await axios.get("/posts/profile/" username)
CodePudding user response:
In addition to the other solutions, you can also use ticks ( ` ) which allow you to do the following:
await axios.get(`/posts/profile/${username}`);