【发布时间】:2021-12-03 19:40:33
【问题描述】:
我将代理设置为 http://localhost:8000/api (适用于其他请求)
在反应中,我正在使用 axios 进行获取请求:
const res = username
? await axios.get("posts/profile/"+username)
: await axios.get("posts/timeline/6120b0e07ea0361eb4982b1c");
当未定义用户名时,第二个条件有效,但当提供用户名时,第一个条件将请求发送到另一个 url: 在运行后端的 VSCode 终端中,这是可见的:
::ffff:127.0.0.1 - - [15/Oct/2021:15:38:12 +0000] "GET /api/profile/posts/profile/matt HTTP/1.1" 404 169
它应该转到 /api/posts/profile/matt 但它却转到上面的那个
在 chrome 控制台中:
xhr.js:210 GET http://localhost:3000/profile/posts/profile/matt 404 (Not Found)
在 POSTMAN 中,api 有效。当我使用完整的 URL 时:
const res = username
? await axios.get("http://localhost:8000/posts/profile/"+username)
: await axios.get("posts/timeline/6120b0e07ea0361eb4982b1c");
使用完整 url 后,应用程序可以正常工作,但是在没有完整 URL 的情况下它应该可以正常工作,因为我已经设置了代理,并且对于其他 get 请求也可以正常工作,即使没有完整 url 的时间线也可以正常工作。
这是反应路由的代码:
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>
)
}
这里是 API(使用正确的 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);
}
});
这可能是什么问题?问题仅发生在配置文件请求(将请求发送到错误的 url)
【问题讨论】:
-
/api路径在哪里发挥作用?您是否在服务器上使用反向代理?您在哪条路线上为前端提供服务? -
代理是:localhost:8000/api,除了配置文件一之外的所有请求都可以正常工作,请参考这个问题:stackoverflow.com/questions/69592894/…
标签: reactjs express axios react-router