GET http://localhost:3000/api/users/:userId 400错误请求? Axios 反应

问题描述

我试图在我的 React 应用程序的客户端显示数据。在我的服务器端通过 id 向单个用户发送获取请求时,我得到 200 ok 状态和用户信息。但是当尝试在客户端进行 axios 调用时,我收到 400 状态错误。我相信这就是我在服务器端获取请求中使用 req.params 的方式。如何重构 GET 请求,以便在客户端获得响应。

控制器

router.get("/:userId",(req,res) => {
      const { userId } = req.params;

        if(!userId){
           return res.status(400).json({message: "user id not found"})
        }

        if(!ObjectId.isValid(userId)){
           return res.status(400).json({ message: "userId  not valid"})
        }

        User.findById(userId,(err,user) => {
            if(err) {
                res.status(500);
                console.log("errr 500")
            } else {
                if(!user)
                res.status(400).json({message:"user not found"});

                res.status(200).json({"user" : user})
            }
        })

    })

反应组件

import React,{ Component } from 'react';
import { Link } from 'react-router-dom'
import axios from 'axios'
import PropTypes from "prop-types";
import { connect } from "react-redux";


import Navbar from '../layouts/navbar'

class userDashboard extends Component {

    state = {
        user: {}
    }


    getUser = () =>{
        const userId = this.props.match.params.id;
           axios.get(`http://localhost:5000/api/users/${userId}`).then(res=>{
               const user = res.data;
               this.setState({
                   user
               })
           }).catch((err)=> console.log(err))
        }

    


    componentDidMount() {
        this.getUser()
    }
    render() {

        const { name } = this.state.user 
        return (
            <div>
                <Navbar />
        <h1 className="title-text">Hello { name }</h1>
            </div>
        );
    }
}

userDashboard.propTypes = {
    // logoutUser: PropTypes.func.isrequired,auth: PropTypes.object.isrequired,};
  const mapStatetoProps = (state) => ({
    auth: state.auth,});
  export default connect(mapStatetoProps)(userDashboard);

server.js

const express = require("express");

const path = require('path');

const mongoose = require("mongoose");

const bodyParser = require("body-parser");

const passport = require("passport");

const cors = require('cors')


const app = express();
const users = require("./controllers/api/users")


app.use(cors());
app.use(

    bodyParser.urlencoded({
        extended: false
    })
);

app.use(bodyParser.json());

app.use(express.static(`${__dirname}/client/build`));


// app.get('/*',res) => {
//     res.sendFile(`${__dirname}/client/build/index.html`)
// })
// app.get('/*',res) => {
//     res.sendFile(path.join(__dirname,'/../','build','index.html'));
//  });

//DATA BASE CONfigURATION

const dbkeys = require("./config/key").mongoURI;

mongoose.connect( 
    dbkeys,{useNewUrlParser: true} )

        .then(()=> console.log("database connection successful"))
        .catch(err => console.log(err))

app.use(passport.initialize());
require("./config/passport")(passport);


app.use("/api/users",users);

// app.use("/api",users)


const port = 5000;

app.listen( port,() => console.log("server us up and running on port 5000!"))

模型

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const ClassworkSchema = new Schema({
    name: String,time: Date,todo: String,isDone: false
});

const OutcomesSchema = new Schema({
    name: String,isDone: false,isApproved: false
})

const MeetupSchema = new Schema({
    name: String,location: String,attended: false
})
const UserSchema = new Schema({
    name: {
      type: String,required: true
    },email: {
      type: String,password: {
      type: String,date: {
      type: Date,default: Date.Now
    },classwork:{type: [ClassworkSchema],default: []},outcomes: [OutcomesSchema],meetups: [MeetupSchema],});


  // const User = mongoose.model('users',UserSchema);
  // const Classwork = mongoose.model('Classwork',ClassworkSchema );

  // module.exports = {
  //   User : User,//   // Classwork : Classwork 
  // }
  module.exports = mongoose.model("users",UserSchema);

解决方法

尝试在 package.json 中添加 "proxy":"http://localhost:5000/" in react 然后使用:

axios.get(`/api/users/${userId}`)...