我將代理設定為 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)
uj5u.com熱心網友回復:
您的相對 URL 的決議方式與您想象的不同。您可以對此進行除錯,但我建議您只使用絕對 URL 來確保您知道它們是如何決議的:
const res = username
? await axios.get("/api/posts/profile/" username)
: await axios.get("/api/posts/timeline/6120b0e07ea0361eb4982b1c");
uj5u.com熱心網友回復:
在帖子作業之前添加斜線:
await axios.get("/posts/profile/" username)
uj5u.com熱心網友回復:
除了其他解決方案,您還可以使用刻度 (`) 來執行以下操作:
await axios.get(`/posts/profile/${username}`);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/322888.html
