简体   繁体   中英

front end react is not sending data to to mongoDB database

THE app is suppose to register the new user and send the new users info to the MongoDB, but when i attempt to register the user it throws an error of 500 internal error. the console says the error is in the user file, the terminal say this is the error, Proxy error: Could not proxy request /api/users from localhost:3000 to https://localhost:5000 . [1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (EPROTO). I've already tried changing the proxy in the packet.json by giving it a different path and target but its not working. maybe i'm overlooking something. enter code here

import React, { useReducer } from 'react';
import axios from 'axios';
import AuthContext from './authContext';
import authReducer from './authReducer';
import {
 REGISTER_SUCCESS,
 REGISTER_FAIL,
 USER_LOADED,
 AUTH_ERROR,
 LOGIN_SUCCESS,
 LOGIN_FAIL,
 LOGOUT,
 CLEAR_ERRORS 
 } from '../types';

const AuthState = props => {
//initial state 
const initialState = {
    token: localStorage.getItem('token'),
    isAuthenticated: null,
    user: null,
    loading: true,
    error: null    
};
const [ state, dispatch ] = useReducer(authReducer, initialState);

// load user
const loadUser = () => console.log('load user') ;

// register user
const register = async formData => {
  const config = {
      headers: {
          'Content-Type': 'application/json'
      }
  }
  try {
   const res = await axios.post('api/users', formData, config);
   dispatch({
       type: REGISTER_SUCCESS, 
       payload: res.data 
   });
  } catch (err){
    dispatch({
        type: REGISTER_FAIL, 
        payload: err.response.data.msg
    });

  }
}

// login user
const login = () => console.log('login') ;


//logut
const logout = () => console.log('logout') ;


 // clear errors
 const clearErrors = () => console.log('clearErrors') ;

 return (
    <AuthContext.Provider
    value= {{
       token: state.token,
       isAuthenticated: state.isAuthenticated,
       loading: state.loading,
       user: state.user,
       error: state.error,
       register,
       loadUser,
       login,
       logout,
       clearErrors
    }}>

    {props.children}

    </AuthContext.Provider>
 );
 };
  export default AuthState;

//this is my server.js file with the routes

  const express = require('express');
  const connectDB = require('./config/db')

  //connect MongoDB
   connectDB();


   const app = express();

   //init middleware
   app.use(express.json({extended: false}));

   app.get('/', (req, res) => res.json({ msg: 'hello welcome'})
   );

   //define routes 
   app.use('/api/users', require('./routes/users'));
   app.use('/api/auth', require('./routes/auth'));
   app.use('/api/contacts', require('./routes/contacts'))

   const PORT = process.env.PORT || 5000;

   app.listen(PORT, () => console.log(`server is working on ${PORT}`))

// this is mongoDB code

  const mongoose = require('mongoose');
  const config = require('config');
  const db = config.get('mongoURI');

  const connectDB = async () =>{
  try{ await
    mongoose.connect(db, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false

  });
 console.log('mongo connected..')

 } catch (err){
 console.log(err.message);
 process.exit(1)
  }
 };
 module.exports = connectDB;

// this the users file where the console is throwing the 500 internal error.

      const express = require('express');
      const router = express.Router();
      const bcrypt = require('bcryptjs');
      const jwt = require('jsonwebtoken');
      const config = require('config');
       const { check, validationResult } = require('express-validator');

       const User = require('../models/User')

    // This route  Post request to api/users,
   // description   register a  user,
   // access to public to register an become a user
   router.post('/',  [
   check('name', 'Name is require').not().isEmpty(),
   check('email', 'please include email').isEmail(),
   check('password', 'enter a password with atleast 6 characters'
  ).isLength({min: 6})

  ],
   async (req, res) =>{
     const errors = validationResult(req);
      if(!errors.isEmpty()){
        return res.status(400).json({ errors: errors.array()});
   }
    const { name, email, password } = req.body; 
    try{
         let user = await User.findOne({email});
      if(user){
         return res.status(400).json({msg: 'user already exist'})
     }
      user  = new User({
        name,
        email,
        password
     });
      const salt = await bcrypt.genSalt(10);
      user.password = await bcrypt.hash(password, salt);
      await user.save();

     // object to send in the token
      const payload = {
        user: {
            id: user.id
        }
     }
      jwt.sign(payload, config.get('jwtSecret'), {
        expiresIn: 36000
       }, (err, token) => {
          if(err) throw err;
            res.json({token});

      });

     } catch (err){
       console.log(err.message);
       res.status(500).send('server error')
     }
    });


      module.exports = router;

I figure out the problem!!! I had an unexpected token in my users file that simple colon was interfering with the code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM