Logging in the User upon Registration Error

In the Logging in the User upon Registration lecture I can register a new user… But at the same time I keep getting 2 errors:

logging_user_registration

Plus I can’t move to the main page after submission. What is causing these errors?

Here’s my user.js code:

const auth = require("../middleware/auth");

const bcrypt = require("bcrypt");

const _ = require("lodash");

const { User, validate } = require("../models/user");

const express = require("express");

const router = express.Router();

router.get("/me", auth, async (req, res) => {

         const user = await User.findById(req.user._id).select("-password");

         res.send(user);

 });

 router.post("/", async (req, res) => {

        const { error } = validate(req.body);

       if (error) return res.status(400).send(error.details[0].message);

       let user = await User.findOne({ email: req.body.email });

      if (user) return res.status(400).send("User already registered.");

      user = new User(_.pick(req.body, ["name", "email", "password"]));

      bcrypt.genSalt(10, function (_err, salt) {

      bcrypt.hash(user.name, salt, function (_err, hash) {

      // Store hash in your password DB.

       user.password = hash;

      });

   });



        await user.save();

        const token = user.generateAuthToken();

        res

         .header("x-auth-token", token)

         .header("access-control-expose-headers", "x-auth-token")

         .send(_.pick(user, ["_id", "name", "email"]));

  });

module.exports = router;

And here’s my registerForm.js:

import React from "react";

import Joi from "joi-browser";

import Form from "./common/form";

import * as userService from '../services/userService'; // Import methods *

class RegisterForm extends Form {

      state = {

      data: { username: "", password: "", name: "" },

     errors: {}

    };

    schema = {

    username: Joi.string()

   .required()

  .email()

  .label("Username"),

   password: Joi.string()

      .required()

      .min(5)

      .label("Password"),

     name: Joi.string()

        .required()

      .label("Name")

    };

   doSubmit = async () => {

       try {

         const response = await userService.register(this.state.data);

        console.log(response);

        localStorage.setItem('token', response.header['x-auth-token']);

       this.props.history.push("/");

     }

    catch (ex) {

           if (ex.response && ex.response.status === 400) {

          const errors = {...this.state.errors};

          errors.username = ex.response.data;

          this.setState({ errors });

        }

    }

// Call the server

//console.log("Submitted");

// Apply email, name and password data to register

      userService.register(this.state.data);

  };

  render() {

       return (

           <div>

             <h1>Register</h1>

              <form onSubmit={this.handleSubmit}>

                 {this.renderInput("username", "Username")}

                {this.renderInput("password", "Password", "password")}

                {this.renderInput("name", "Name")}

                {this.renderButton("Register")}

            </form>

        </div>

        );

      }

    }

export default RegisterForm;

Mine was status: 500.
One thing I know is bcrypt does not work for me so I install bcryptjs instead. Therefor, in auth.js and users.js we should have
const bcrypt = require(“bcryptjs”);

Hope this helps and happy coding!

1 Like

@ComTamSuonMo I tried bcryptjs and it still didn’t work… I got the same error. Thanks anyways.

So I made a syntax error in my localStorage function. If you look down below I was using the word “header” when I should’ve been using “headers”… Overall when I click on the Register button the app takes me to the home page as expected, but I still keep getting that error “400 (Bad Request)” and I don’t know why. For now I’m just going to move on.

localStorage.setItem(‘token’, response.header[‘x-auth-token’]);