1
votes

I am working on a MERN stack and I am trying to display a single user's data on its own page. The route works on the server-side in Postman, I am able to get the user by Id. But on the client-side I get a 400 bad request when trying to get the user information with axios from that route. could their be a problem with any of my endpoints?

What localhost shows in my console

Error in the console

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'
// import './userDashboard.css'
class userDashboard extends Component {

    state = {
        user: {}
    }

    getUser = () =>{
    const userId = this.props.match.params.userId
       axios.get('/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);

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

    })

server.js

const express = require("express");

const path = require('path');

const mongoose = require("mongoose");

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

const passport = require("passport");


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



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!"))

Schema

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
Please return a message for every 400 error in the backend and check in which case the 400 error is returned. - First Arachne
I might know the solution to your problem, could you add the "User" collection Schema? - Kevin Buguecio
I added my Schema to the original post. and I am checking on those 400 error messages on the backend - Wadaygo
If it works on Postman, the problem probably isn't on server-side, can you post a most detailed message of the error ? Open your console , go to Network tab, so finds the request then click on it, then go to the Response tab, what appears ? - Eduardo Fellipe
@EduardoFellipe I found the response in the network tab, it is in the controller code. it is the second 400 message error with userId not valid. Do have any idea why this is. - Wadaygo

1 Answers

0
votes

You need to include the server side localhost endpoint in your GET request from the client side.

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

You are requesting a response from the server side , so it is required to include the correct path to which the response should travel.

You will need to include this path in all of the requests you send from the client side to the server side. I recommend using a proxy in the client side package.json as below,

"proxy":"http://localhost:5000"

This will let you write your endpoint path as you have done in your GET request implementation.

For the CORS error,

Install CORS in your server side package.json as npm install cors

Then import CORS to your server.js as const cors = require('cors');

Then use CORS as middleware app.use(cors());