GET http://localhost:3000/api/users/:userId 400 (Bad Request) ? Axios React

Viewed 322

I trying to display data on the client-side of my react application. when sending a get request for single user by id on my server-side I get a 200 ok status and the user information. But when trying to make an axios call on the client-side i get 400 status error. I believe it is how I use req.params in the server-side get request. how can I refactor the GET request so that I can get the response on the client-side.

Controller

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

    })

React Component

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('/*', (req, res) => {
//     res.sendFile(`${__dirname}/client/build/index.html`)
// })
// app.get('/*', (req, 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!"))

Models

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,
    time: Date,
    todo: String, 
    isDone: false,
    isApproved: false
})

const MeetupSchema = new Schema({
    name: String,
    time: Date,
    location: String,
    attended: false
})
const UserSchema = new Schema({
    name: {
      type: String,
      required: true
    },
    email: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true
    },
    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);
1 Answers

try adding "proxy":"http://localhost:5000/" in the package.json in react then use :

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