Необходимо знать концепцию маршрутизации в React - PullRequest
0 голосов
/ 26 мая 2020

всякий раз, когда я пытаюсь выполнить «получить» Request of api »(api/posts/${id})«, я получаю сообщение об ошибке Cannot GET / posts / api / posts / 5c804ec6ad029f21201c686e

Я не могу понять, где слово "сообщения" добавляется в мой вызов API с помощью ax ios. Я тщательно проверил свой код, но не могу найти ошибку. Я думаю, что это связано с маршрутизацией компонентов. Пожалуйста, найдите файлы ниже. дайте мне знать, где мне его не хватает.

Backend файл: -

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 }
        })

    }
}

React component, откуда я нажимаю ссылку: -

<Link to={`/posts/${_id}`} className="btn btn-primary">
        Discussion{' '}
        {comments.length > 0 && (
        <span className='comment-count'>{comments.length}</span>
   )}
</Link>

App. js component: -

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;

1 Ответ

0 голосов
/ 26 мая 2020

Вы не добавили / к URL-адресу запроса api. В таком случае он добавляет URL-адрес запроса относительно текущего, а не абсолютного

const res = await axios.get(`/api/posts/${id}`); // make an API request like this
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...