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:
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;