実現したいこと
getリクエストでHTMLが返却されてしまいます(apiに到達できていないと思います。)
前提:Viteでプロジェクトを作成しています。
タイトルの件につきまして、どれだけ確認しても解決策が分からない為ご教授頂けますと幸いです。
発生している問題・分からないこと
APIがうまく到達していないように思えます。
エラーメッセージ
error
1エラーではありませんが、 2{data: '<!doctype html>\n<html lang="en">\n <head>\n <scr….jsx?t=1739837589140">\x3C/script>\n </body>\n</html>', status: 200, statusText: 'OK', headers: AxiosHeaders, config: {…}, …} 3config 4: 5{transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} 6data 7: 8"<!doctype html>\n<html lang=\"en\">\n <head>\n <script type=\"module\">\nimport RefreshRuntime from \"/@react-refresh\"\nRefreshRuntime.injectIntoGlobalHook(window)\nwindow.$RefreshReg$ = () => {}\nwindow.$RefreshSig$ = () => (type) => type\nwindow.__vite_plugin_react_preamble_installed__ = true\n</script>\n\n <script type=\"module\" src=\"/@vite/client\"></script>\n\n <meta charset=\"UTF-8\" />\n <link rel=\"icon\" type=\"image/svg+xml\" href=\"/vite.svg\" />\n <link rel=\"stylesheet\" href=\"/src/styles.css\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n <title>Vite + React</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/main.jsx?t=1739837589140\"></script>\n </body>\n</html>" 9headers 10: 11AxiosHeaders {cache-control: 'no-cache', content-length: '742', content-type: 'text/html', date: 'Tue, 18 Feb 2025 00:13:12 GMT', etag: 'W/"2e6-sFtc7NHEO0UE8RiyMUChkYL2xjU"', …} 12request 13: 14XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} 15status 16: 17200 18statusText 19: 20"OK" 21[[Prototype]] 22: 23Object
該当のソースコード
posts.js
1router.get("/timeline/:userId", async (req, res) => { 2 3 conso.log("API到達テスト") 4 5 try { 6 7 // 自分の投稿 8 9 const currentUser = await User.findById(req.params.userId); 10 11 const userPosts = await Post.find({ userId: currentUser._id }); 12 13 // フォロー中の投稿 14 15 const friendPosts = await Promise.all( 16 17 currentUser.followings.map((friendId) => { 18 19 return Post.find({ userId: friendId }) 20 21 }) 22 23 ); 24 25 // return res.status(200).json(userPosts.concat(...friendPosts)); 26 27 return res.send("API成功テスト") 28 29 } catch (err) { 30 31 // return res.status(500).json(err); 32 33 return res.send("API失敗テスト") 34 35 } 36 37 }); 38 39→このファイルで記述しているconsoleは何も表示されていませんので、そもそもこのapiまで到達できていないと思っています。
server.js
1const PORT = 5001; 2 3mongoose.connect(process.env.MONGOURL).then(()=> { 4 console.log("接続完了") 5}).catch((err)=> { 6 console.log(err) 7}); 8app.use(express.json()); 9app.use("/api/posts", postsRoute) 10app.get('/', (req, res) => { 11 res.send("hello express"); 12}); 13app.listen(PORT, () => { 14 console.log("listenテスト") 15}) 16 17→コマンドラインにconsole内容("接続完了"/"listenテスト")が表示されますので問題なく接続はできていると思います。
package.json(フロントエンド)
1"proxy": "http://localhost:5001/api" 2 3→5000は使用済みでしたので、5001を指定、server.jsでのPORTも5001にしているので、問題ないかと思います。
TimeLine.jsx
1const TimeLine = () => { 2 const [posts, setPosts] = useState([]); 3 4 useEffect(() => { 5 const fetchPosts = async () => { 6 const response = await axios.get("/posts/timeline/67a6a4066276f88fa966ca65") 7 console.log(response); 8 setPosts(response.data) 9 }; 10 fetchPosts(); 11 },[]); 12 return ( 13 <div className="timeline"> 14 <div className="timelineWrapper"> 15 <Share /> 16 </div> 17 </div> 18 ) 19} 20 21→userのidとパス指定も上記までのproxyやミドルウェアのルートを踏まえて間違い無いように思えます。
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
解決できませんでした
補足
特になし
