【发布时间】:2020-09-13 15:46:52
【问题描述】:
每当我尝试“获取”api请求时“(api/posts/${id})”
我收到错误提示无法获取 /posts/api/posts/5c804ec6ad029f21201c686e
我无法弄清楚在我使用 axios 的 api 调用中“posts”这个词的位置。 我彻底检查了我的代码,但我无法发现这个错误。我认为这与组件的路由有关。请在文件下方找到。让我知道我错过了它。
后端文件:-
const express = require("express");
const router = express.Router();
const { check, validationResult } = require("express-validator");
const auth = require("../../middleware/auth");
const Post = require("../../models/Post");
const User = require("../../models/User");
const Profile = require("../../models/Profile");
//@route DELETE api/posts/:id
//@desc Delete Post by Id
//@access Private
router.delete("/:id", auth, async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post) {
return res.status(404).json({ msg: 'Post not found' })
}
// check user
if (post.user.toString() !== req.user.id) {
return res.status(401).json({ msg: 'User not authorized' })
}
await post.remove();
res.json({ msg: 'Post deleted' });
} catch (err) {
console.log(err.message);
if (err.kind === 'ObjectId') {
return res.status(404).json({ msg: 'Post not found' })
}
res.status(500).send('Server Error');
}
});
module.exports = router;
server.js:-
const express = require("express");
const connectDB = require("./config/db");
const app = express();
// Connect Database
connectDB();
// Init Middleware
app.use(express.json({ extended: false }));
app.get("/", (req, res) => res.send(`API Running`));
// define Routes
app.use('/api/users', require(`./routes/api/users`));
app.use('/api/auth', require(`./routes/api/auth`));
app.use('/api/profile', require(`./routes/api/profile`));
app.use('/api/posts', require(`./routes/api/posts`));
const PORT = process.env.PORT || 5000
app.listen(PORT, () => { `Server started on port ${PORT}` });
我请求 API 的文件(操作):- post.js :-
import axios from "axios";
import { setAlert } from './alert';
import {
GET_POSTS,
POST_ERROR,
UPDATE_LIKES,
DELETE_POST,
ADD_POST,
GET_POST
} from './types';
// Get post
export const getPost = id => async dispatch => {
try {
const res = await axios.get(`api/posts/${id}`);
dispatch({
type: GET_POST,
payload: res.data
})
} catch (err) {
dispatch({
type: POST_ERROR,
payload: { msg: err.response.statusText, status: err.response.status }
})
}
}
我点击链接的反应组件:-
<Link to={`/posts/${_id}`} className="btn btn-primary">
Discussion{' '}
{comments.length > 0 && (
<span className='comment-count'>{comments.length}</span>
)}
</Link>
App.js 组件:-
import React, { Fragment, useEffect } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Landing from './components/layout/Landing';
import Register from './components/auth/Register';
import Login from './components/auth/Login';
import Alert from './components/layout/Alert';
import Dashboard from './components/dashboard/Dashboard'
import PrivateRoute from './components/routing/privateRoute'
import CreateProfile from './components/profile-forms/CreateProfile';
import EditProfile from './components/profile-forms/EditProfile';
import AddExperience from './components/profile-forms/AddExperience';
import AddEducation from './components/profile-forms/AddEducation';
import Profile from './components/profile/Profile';
import Profiles from './components/profiles/Profiles';
import Posts from './components/posts/Posts';
import Post from './components/post/Post';
// Redux
import { Provider } from 'react-redux';
import store from './store';
import { loadUser } from './actions/auth';
import setAuthToken from './utils/setAuthToken'
import './App.css';
if (localStorage.token) {
setAuthToken(localStorage.token);
}
const App = () => {
useEffect(() => {
store.dispatch(loadUser());
}, []);
return (
<Provider store={store}>
<Router>
<Fragment>
<Navbar />
<Route exact path="/" component={Landing} />
<section className='container'>
<Alert />
<Switch>
<Route exact path="/register" component={Register} />
<Route exact path="/login" component={Login} />
<Route exact path="/profiles" component={Profiles} />
<Route exact path="/profile/:id" component={Profile} />
<PrivateRoute exact path="/dashboard" component={Dashboard} />
<PrivateRoute exact path="/create-profile" component={CreateProfile} />
<PrivateRoute exact path="/edit-profile" component={EditProfile} />
<PrivateRoute exact path="/add-experience" component={AddExperience} />
<PrivateRoute exact path="/add-education" component={AddEducation} />
<PrivateRoute exact path="/posts" component={Posts} />
<PrivateRoute exact path="/posts/:id" component={Post} />
</Switch>
</section>
</Fragment>
</Router>
</Provider>
)
}
export default App;
【问题讨论】:
标签: node.js reactjs react-router react-router-dom