【问题标题】:React/Nodejs: URLs on front-end and back-end don't match , which causes an errorReact/Nodejs:前端和后端的 URL 不匹配,导致错误
【发布时间】:2019-06-03 06:50:47
【问题描述】:

我想在我的应用程序中创建一个公共个人资料页面,但是每当我点击路由时,控制台中就会出现错误。我不明白这是什么问题,请你用你的新眼睛看一下。让我给你更多关于我的问题的信息。

公共路由 - 后端

// @route  POST api/profile/user/:user_id
// @desc   Get profile by user ID
// @access Public
router.get('/user/:user_id', (req, res) => {
  const errors = {};
  Profile.findOne({ user: req.params.user_id })
    .populate('user', ['name', 'email', 'avatar'])
    .then(profile => {
      if (!profile) {
        errors.nonprofile = 'There is no profile for this user';
        res.status(404).json(errors);
      }
      res.json(profile);
    })
    .catch(err =>
      res.status(404).json({ profile: 'There is no profile for this user' })
    );
});

Redux 操作部分

export const getPublicProfileByID = id => dispatch => {
  console.log(id);
  axios
    .get(`api/profile/user/${id}`)
    .then(res => {
      dispatch({
        type: GET_PUBLIC_PROFILE_BY_ID,
        payload: res.data
      });
    })
    .catch(err =>
      dispatch({
        type: GET_PUBLIC_PROFILE_BY_ID,
        payload: null
      })
    );
};

PublicProfile - 反应部分

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Spinner from '../common/Spinner';
import { getPublicProfileByID } from '../../actions/profileActions';
import { Link } from 'react-router-dom';

class PublicProfile extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    console.log(this.props);
    this.props.getPublicProfileByID(this.props.profile._id);
  }

  render() {
    const { profile, loading } = this.props.profile;
    const { auth } = this.props;
    console.log(profile);
    let profileShow;

    if (profile === null || loading) {
      profileShow = <Spinner />;
    } else {
      profileShow = (
        <div className="row">
          <div className="col-md-4" align="center">
            <figure className="figure">
              <img
                src={auth.user.avatar}
                className="figure-img img-fluid rounded"
                alt={auth.user.avatar}
              />
            </figure>
          </div>
          <div className="col-md-6">{profile.bio}</div>
          <div className="col-md-2">
            <ul className="list-group list-group-flush">
              <li className="list-group-item">
                <div className="row">
                  <div className="col">
                    {profile.social ? (
                      <a href={profile.social.facebook} target="_blank">
                        <i className="fab fa-facebook" />
                      </a>
                    ) : null}
                  </div>
                  <div className="col">
                    {profile.social ? (
                      <a href={profile.social.vk} target="_blank">
                        <i className="fab fa-vk" />
                      </a>
                    ) : null}
                  </div>
                  <div className="col">
                    {profile.social ? (
                      <a href={profile.social.instagram} target="_blank">
                        <i className="fab fa-instagram" />
                      </a>
                    ) : null}
                  </div>
                </div>
              </li>
              {profile.country ? (
                <li className="list-group-item">Страна: {profile.country}</li>
              ) : null}
              {profile.city ? (
                <li className="list-group-item">Город: {profile.city}</li>
              ) : null}
              {profile.gender ? (
                <li className="list-group-item">Пол: {profile.gender}</li>
              ) : null}
              {profile.education ? (
                <li className="list-group-item">
                  Образование: {profile.education}
                </li>
              ) : null}
              {profile.languages ? (
                <li className="list-group-item">
                  Языки:{' '}
                  {profile.languages.map(language => (
                    <span key={language}>{language}</span>
                  ))}
                </li>
              ) : null}
            </ul>
          </div>
        </div>
      );
    }

    return (
      <div className="container">
        <div className="row">
          <div className="col align-self-center">{profileShow}</div>
        </div>
      </div>
    );
  }
}

PublicProfile.propTypes = {
  auth: PropTypes.object.isRequired,
  getPublicProfileByID: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  profile: state.profile,
  auth: state.auth
});

export default connect(
  mapStateToProps,
  { getPublicProfileByID }
)(PublicProfile);

Redux Reducer 部分

import {
  GET_PROFILE,
  PROFILE_LOADING,
  CLEAR_CURRENT_PROFILE,
  GET_PUBLIC_PROFILE_BY_ID
} from '../actions/types';

const initialState = {
  profile: null,
  profiles: null,
  loading: false
};

export default function(state = initialState, action) {
  switch (action.type) {
    case PROFILE_LOADING:
      return {
        ...state,
        loading: true
      };
    case GET_PROFILE:
      return {
        ...state,
        profile: action.payload,
        loading: false
      };
    case GET_PUBLIC_PROFILE_BY_ID:
      return {
        ...state,
        profile: action.payload,
        loading: false
      };
    case CLEAR_CURRENT_PROFILE:
      return {
        ...state,
        profile: null
      };
    default:
      return state;
  }
}

app.js 中的公共路由

<Route exact path="/leaders/:id" component={PublicProfile} />

浏览器中的网址

控制台出错

【问题讨论】:

  • 你的nodejs服务器运行的端口是什么,因为你调用的3000是反应默认端口而不是你的后端端口
  • 所有其他路线都可以正常工作。所以我想问题不在于端口。
  • 如果其他路由正常工作,那么在查询您的 useId 时未定义,在这种情况下,您发送 404 请参阅后端的 catch 部分
  • 领导在这里做什么.get(api/profile/user/${id}),而你正在点击/leader/api/profile/user/
  • 控制台上看不到console.log(id),id没有被设置为特定数据。

标签: node.js reactjs redux


【解决方案1】:

您将前端 URL 与后端 Restful http URL 混淆了, 您需要为 react 和 node 应用程序启动不同的两个端口, 您正在将 React-Route 的逻辑与 node-Express 逻辑混合, 当localhost:3000 代表反应时,
您应该为后端应用程序选择不同的端口号, 保持服务器监听该端口, 然后对该网址进行请求并传达您的数据。 您需要正确配置您的应用。
例如。
localhost:3000/leaders/leader/2 用于您的前端, 发出服务器请求,例如, localhost:8000/api/profile/user/2 其中 2 是 ${id} 用于后端代码。

【讨论】:

    【解决方案2】:

    我注意到一个问题,在您的 api 路由中,它想找到一个 Profileuser 字段与您传递的参数匹配。

    router.get('/user/:user_id', (req, res) => {
      const errors = {};
      Profile.findOne({ user: req.params.user_id })
    

    但是,您似乎在动作创建器中传递了错误的值。您正在传递个人资料的 ID。

      componentDidMount() {
        console.log(this.props);
        this.props.getPublicProfileByID(this.props.profile._id);
      }
    

    相反,您需要传入拥有此个人资料的用户的 ID。

      componentDidMount() {
        console.log(this.props);
        this.props.getPublicProfileByID(this.props.profile.user._id);
      }
    

    其次,您的axios 调用似乎有错误

      axios
        .get(`api/profile/user/${id}`)
    

    【讨论】:

    • 如果我把用户放在那里它会抛出一个错误:无法读取未定义的属性'_id'。
    • 为什么我的 url 看起来像这样:localhost:3000/api/profile/user/5cf2828fb3ae541c8491634b404(未找到),而应该是这样:localhost:3000/api/user/5cf2828fb3ae541c8491634b404(未找到)
    • @NZMAI,等等,但是在您的路线定义中,您为您的路线评论了以下内容 //route POST api/profile/user/:user_id
    • 如果有效,请点赞并接受@ChristopherNgo 的回答。
    • 是的,但我认为 api 和用户之间的“配置文件”不允许我继续。哦,它碰巧在那里?
    【解决方案3】:

    我已经解决了这个问题,我应该使用findById 方法,参数应该是req.params.id。所以一个有效的代码看起来像这样。

    // @route  POST api/profile/user/:user_id
    // @desc   Get profile by user ID
    // @access Public
    
    router.get('/user/:id', (req, res) => {
      const errors = {};
      Profile.findById(req.params.id)
        .populate('user', ['name', 'email', 'avatar'])
        .then(profile => {
          if (!profile) {
            errors.nonprofile = 'There is no profile for this user';
            res.status(404).json(errors);
          }
          res.json(profile);
        })
        .catch(err =>
          res.status(404).json({ profile: 'There is no profile for this user' })
        );
    });
    

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 2021-06-16
      • 2018-04-21
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 2021-10-16
      • 1970-01-01
      相关资源
      最近更新 更多