"Cannot get" 当我用 React 和 Axios 做 API 请求时

"Cannot get" when I do API request with React and Axios

我对 API 请求使用 React 和 Axios。

我的 API 请求有问题;我得到:

Cannot GET /posts/byId/1

当我在 http://localhost:3002/posts/byId/1 执行 GET 时,我的所有其他请求都有效。

有人有解决办法吗?


我的路线:

const express = require('express');
const router = express.Router();
const { Posts } = require('../models');

router.get('/', async (req, res) => {
    const listOfPosts = await Posts.findAll();
    res.json(listOfPosts);
});

router.get('/byId/:id', async (req, res) => {
    const id = req.params.id;
    const post = await Posts.findByPk(id);
    res.json(post);
});

router.post('/', async (req, res) => {
    const post = req.body;
    await Posts.create(post);
    res.json(post);
});

module.exports = router;

我的App.js:

import './App.css';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './pages/Home';
import CreatePost from './pages/CreatePost';
import Post from './pages/Post';

function App() {
    return (
        <div className="App">
            <Router>
                <div className="navbar">
                    <Link to="createPost"> Create A Post </Link>
                    <Link to="/"> Home Page </Link>
                </div>
                <Routes>
                    <Route path="/" element={<Home />} />
                    <Route path="/createPost" element={<CreatePost />} />
                    <Route path="/post/:id" element={<Post />} />
                </Routes>
            </Router>
        </div>
    );
}

export default App;

我的 Post.js :

import React, { useEffect } from 'react';
import { useParams } from 'react-router-dom';
import axios from 'axios';

function Post() {
    let { id } = useParams();

    useEffect(() => {
        axios.get(`http://localhost:3002/posts/byId/${id}`).then((response) => {});
    });

    return <div>{id}</div>;
}

export default Post;

您的路线不是 /posts/byId/:id,而只是 /byId/:id

更新: 我不得不卸载并安装 nodeJS(node_modules) 并解决了问题