Related
When I post the data for my Auth the console throws this error ** 500 (Internal Server Error) ** I think the problem is with my server, first check the database and the data is in the cluster
but the data does not work in my client. I know that this type of problem is often on the server. I've been searching for several hours and I can't figure it out.
This is the index
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js';
import userRoutes from './routes/users.js';
const app = express();
app.use(bodyParser.json({ limit: '30mb', extended: true }))
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }))
app.use(cors());
app.use('/posts', postRoutes);
app.use('/users', userRoutes);
const CONNECTION_URL = '**THIS_IS_MY_MONGO_DB;
const PORT = process.env.PORT|| 5000;
mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
.catch((error) => console.log(`${error} did not connect`));
mongoose.set('useFindAndModify', false);
The users.js route
import express from 'express';
import { signin, signup } from '../controllers/user.js';
const router = express.Router();
router.post('/signin', signin);
router.post('/signup', signup);
export default router;
The user controller
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import User from "../models/user.js";
export const signin = async (req, res) => {
const { email, password} = req.body;
try {
const existingUser = await User.findOne({ email });
if(!existingUser) return res.status(404).json({ message: "El usuaruio no existe."});
const isPasswordCorrect = await bcrypt.compare(password, existingUser.password);
if(!isPasswordCorrect) return res.status(400).json({ message: "Credenciales invalidas."});
const token = jwt.sing({ email: existingUser.email, id: existingUser._id }, 'test', { expiresIn: "1h" });
res.status(200).json({ result: existingUser, token});
} catch (error) {
res.status(500).json({ message: 'Algo salio mal.' });
}
}
export const signup = async (req, res) => {
const { email, password, confirmPassword, firstName, lastName } = req.body;
try {
const existingUser = await User.findOne({ email });
if(existingUser) return res.status(400).json({ message: "El usuaruio ya existe."});
if(password !== confirmPassword) return res.status(400).json({ message: "Las contraseñas no coinciden."});
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({ email, password: hashedPassword, name: `${firstName} ${lastName}` })
const token = jwt.sing({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });
res.status(200).json({ result, token});
} catch (error) {
res.status(500).json({ message: 'Algo salio mal.' });
}
}
The index api
import axios from 'axios';
const API = axios.create({ baseURL: 'http://localhost:5000' })
export const fetchPosts = () => API.get('/posts');
export const createPost = (newPost) => API.post('/posts', newPost);
export const likePost = (id) => API.patch(`/posts/${id}/likePost`);
export const updatePost = (id, updatedPost) => API.patch(`/posts/${id}`, updatedPost);
export const deletePost = (id) => API.delete(`/posts/${id}`);
export const signIn = (formData) => API.post('/users/signin', formData);
export const signUp = (formData) => API.post('/users/signup', formData);
export const signup = async (req, res) => {
const { email, password, confirmPassword, firstName, lastName } = req.body;
try {
const existingUser = await User.findOne({ email });
if(existingUser) return res.status(400).json({ message: "El usuaruio ya existe."});
if(password !== confirmPassword) return res.status(400).json({ message: "Las contraseñas no coinciden."});
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({ email, password: hashedPassword, name: `${firstName} ${lastName}` })
// you have typo in next line
const token = jwt.sing({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });
// replace it by:
const token = jwt.sign({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });
res.status(200).json({ result, token});
} catch (error) {
res.status(500).json({ message: 'Algo salio mal.' });
}
}
So I know there are tons of similar questions out there, and I've read most of them in the past few days. However I didn't find any solution to my problem. The app is about users can post memories(cards) etc... Point is, when I create a new card with POST request, there is no problem, but when I want to sign up a user then all hell breaks loose and throws this error:
(node:2732) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property 'firstName' of 'req.body' as it is undefined.
at signup (file:///E:/projects/personal/memories-app/backend/controllers/user.controller.js:39:13)
at Layer.handle [as handle_request] (E:\projects\personal\memories-app\backend\node_modules\express\lib\router\layer.js:95:5)
at next (E:\projects\personal\memories-app\backend\node_modules\express\lib\router\route.js:137:13)
I don't know that could be the problem, because other functions work so dunno really.
Here are the codes
server.js
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
import postRoutes from './routes/posts.routes.js';
import userRoutes from './routes/users.routes.js';
const app = express();
dotenv.config();
app.use(express.json({ extended: true }));
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use('/posts', postRoutes);
app.use('/users', userRoutes);
app.get('/', (req, res) => {
res.send('Hello to Memories API');
});
const PORT = process.env.PORT || 5000;
mongoose
.connect(process.env.CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() =>
app.listen(PORT, () => console.log(`Server running on port: ${PORT}`))
)
.catch((error) => console.log(error.message));
mongoose.set('useFindAndModify', false);
user.model.js
import mongoose from 'mongoose';
const userSchema = mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
id: { type: String },
});
export default mongoose.model('User', userSchema);
the sign up method from user.controller.js
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import User from '../models/user.js';
export const signup = async (res, req) => {
const { firstName, lastName, email, password, confirmPassword } = req.body;
try {
const existingUser = await User.findOne({ email });
if (existingUser)
return res.status(400).json({ message: 'User already exists' });
if (password !== confirmPassword)
return res.status(400).json({ message: "Passwords don't match" });
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({
email,
password: hashedPassword,
name: `${firstName} ${lastName}`,
});
const token = jwt.sign(
{ email: result.email, id: result._id },
'test',
{
expiresIn: '1h',
}
);
res.status(200).json({ result, token });
} catch (error) {
res.status(500).json({ message: 'Something went wrong.' });
}
};
and just to see the createPost method (which works) from post.controller.js
import PostMessage from '../models/postMessage.js';
import mongoose from 'mongoose';
export const createPost = async (req, res) => {
const post = req.body;
console.log(post);
const newPost = new PostMessage(post);
try {
await newPost.save();
res.status(201).json(newPost);
} catch (error) {
res.status(409).json({ message: error.message });
}
};
And there is no problem with the front-end because when I simply console.log the req, I can see the body, but if I were to clg the req.body, then it is undefined. I've tried it with postman also, but no luck.
I would appreciate any insight on this! Thanks in advance!
You need to swap the order of res and req in the signup function, replace:
export const signup = async (res, req) => {
by:
export const signup = async (req, res) => {
Your User model does not have a firstName, lastName, and confirmPassword types use { name, email, password, } = req.body to sign up a new user.
In your project frontend use
name email, password, confirmPassword to register a use and email, password to log users in.
I am making full stack app and learn from tutorials and videos . I have a problem with GET request to get information about user which is login in the system. I use Postman to check the requests. When I add user with /login , the Postman look user's accesstoken code. I copy his code and paste it in authorization key in headers in Postman and when I change the URL in localhost to /infor to get information about this user and send it. But it say me "Invalid Authentication". I can't find the wrong. I think the problem is in controllers/userCtrl.js in getUser function. Can you help me?
I put the code:
server.js
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser')
const app = express()
app.use(express.json())
app.use(cookieParser())
app.use(cors())
// Use temp files instead of memory for managing the upload process.
app.use(fileUpload({
useTempFiles: true
}))
// Routes
app.use('/user', require('./routes/userRouter'))
// Connect to Mongodb
const URL = process.env.MONGO_URL
mongoose.connect(URL,{
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true
}, err =>{
if(err) throw err;
console.log('Connected to MongoDB')
})
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log('Server is running on port', PORT)
})
.env
MONGO_URL = ***********
ACCESS_TOKEN_SECRET = ***********
REFRESH_TOKEN_SECRET = *************
routes/userRouter.js
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser')
const app = express()
app.use(express.json())
app.use(cookieParser())
app.use(cors())
// Use temp files instead of memory for managing the upload process.
app.use(fileUpload({
useTempFiles: true
}))
// Routes
app.use('/user', require('./routes/userRouter'))
// Connect to Mongodb
const URL = process.env.MONGO_URL
mongoose.connect(URL,{
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true
}, err =>{
if(err) throw err;
console.log('Connected to MongoDB')
})
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log('Server is running on port', PORT)
})
models/userModel.js
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
},
role: {
type: Number,
default: 0
},
cart: {
type: Array,
default: []
}
}, {
timestamps: true
})
module.exports = mongoose.model('Users', userSchema)
middleware/auth.js
const jwt = require('jsonwebtoken')
const auth = (req, res, next) => {
try{
const token = req.header("Authorization")
if(!token) return res.status(400).json({ msg: "Invalid Authentication" })
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if(!err) return res.status(400).json({msg: "Invalid Authentication" })
req.user = user
next()
})
} catch (err) {
return res.status(500).json({msg: err.message})
}
}
module.exports = auth
controllers/userCtrl.js
const Users = require('../models/userModel')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const userCtrl = {
register: async (req, res) => { // async before a function means one simple thing: a function always returns a promise.
try{
const { name, email, password } = req.body
const user = await Users.findOne({ email }) // wait until the promise resolves
if(user) return res.status(400).json({msg: "The email already exists"})
if(password.length < 6)
return res.status(400).json({msg: "Password is at least 6 characteres long."})
//Password encryption
const passwordHash = await bcrypt.hash(password, 10)
const newUser = new Users({
name, email, password: passwordHash
})
// save mongodb
await newUser.save()
//then create jsonwebtoken to authentication
const accesstoken = createAccessToken({ id: newUser._id })
const refreshtoken = createRefreshToken({ id: newUser._id })
res.cookie('refreshtoken', refreshtoken, {
httpOnly: true,
path: '/user/refresh_token'
});
res.json({accesstoken})
} catch(err){
return res.status(500).json({msg: err.message})
}
},
login: async (req, res) => {
try{
const {email, password} = req.body;
const user = await Users.findOne({email})
if(!user) return res.status(400).json({msg: "User does not exist."})
const isMatch = await bcrypt.compare(password, user.password)
if(!isMatch) return res.status(400).json({msg: "Incorrect password"})
// if login success, create access token and refresh token
const accesstoken = createAccessToken({ id: user._id })
const refreshtoken = createRefreshToken({ id: user._id })
res.cookie('refreshtoken', refreshtoken, {
httpOnly: true,
path: '/user/refresh_token'
});
res.json({accesstoken})
} catch(err){
return res.status(500).json({msg: err.message})
}
},
logout: async (req, res)=> {
try{
res.clearCookie('refreshtoken', {path: '/user/refresh_token'})
return res.json({msg: "Logged out"})
}catch(err){
return res.status(500).json({msg: err.message})
}
},
refreshToken: (req, res) => {
try{
const rftoken = req.cookies.refreshtoken
if(!rftoken) return res.status(400).json({msg: "Please login or Register"})
jwt.verify(rftoken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if(err) return res.status(400).json({msg: "Please login or Register"})
const accesstoken = createAccessToken({id: user.id})
res.json({ accesstoken })
})
}catch (err) {
return res.status(500).json({msg: err.message})
}
},
getUser: async (req, res) => { // problem
try{
const user = await (await Users.findById(req.user.id)).isSelected('-password')
if(!user) return res.status(400).json({ msg: "Useer does not exist."})
res.json(req.user)
}catch (err) {
return res.status(500).json({msg: err.message})
}
}
}
const createAccessToken = (user) => {
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1d' })
}
const createRefreshToken = (user) => {
return jwt.sign(user, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '7d' })
}
module.exports = userCtrl
For your middle ware for getting the token (auth function)
const { authorization } = req.headers
if (!authorization) {
console.log('[No Authorization Code]');
return res.status(401).send({ message: 'Unauthorized' });
}
if (!authorization.startsWith('Bearer')) {
console.log('[Authorization need to start with Bearer]')
return res.status(401).send({ message: 'Unauthorized' });
}
const split = authorization.split('Bearer ')
if (split.length !== 2) {
console.log('[Invalid Authorization Param')
return res.status(401).send({ message: 'Unauthorized' });
}
const token = split[1] //this is your token to use with jwt.verify
When you sending the token in postman, select Bearer Token
When you start creating your frontend, the codes should be equivalent to the following fetch request
fetch('/api/path', { method: 'GET', headers: { "Authorization": `Bearer ${token}`}}).(res => res.json())
May change method to your desire method (e.g get or post), and the token will be the the jwt token
In localhost, deserializeUser is being called, and there was no problem.
But after we deploy our app to ec2 using nginx(react), deserializeUser is never called.
const express = require("express");
const cors = require("cors");
const path = require("path");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const dotenv = require("dotenv");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const passport = require("passport");
const flash = require("connect-flash");
const authRouter = require("./routes/auth");
const calendarRouter = require("./routes/calendar");
const healthPillRouter = require("./routes/healthPill");
const { sequelize } = require("./models");
const passportConfig = require("./passport");
dotenv.config();
const app = express();
sequelize
.sync()
.then(() => {
console.log("db 연결 성공");
})
.catch(console.error);
passportConfig(passport);
app.set("view engine", "pug");
app.use(morgan("combined"));
app.use(cors({ origin: "http://13.124.67.98", credentials: true }));
app.use("/", express.static(path.join(__dirname, "public")));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
session({
resave: false,
saveUninitialized: false,
secret: process.env.COOKIE_SECRET,
cookie: {
httpOnly: true,
secure: false,
},
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use("/", authRouter);
app.use("/", calendarRouter);
app.use("/", healthPillRouter);
app.listen(4000, () => {
console.log("실행중");
});
app.set("port", process.env.PORT || 8001);
// if (process.env.NODE_ENV === "production") {
// app.use(morgan("combined"));
// } else {
// app.use(morgan("dev"));
// }
app.use(express.static(path.join(__dirname, "public")));
app.use(cookieParser(process.env.COOKIE_SECRET));
const sessionOption = {
resave: false,
saveUninitialized: false,
secret: process.env.COOKIE_SECRET,
cookie: {
httpOnly: true,
secure: false,
},
};
// if (process.env.NODE_ENV === "production") {
// sessionOption.proxy = true;
// sessionOption.cookie.secure = true;
// }
app.use(session(sessionOption));
app.use(flash());
this is our app.js
and the bottom is our router code.
<auth.js>
const express = require("express");
const passport = require("passport");
const bcrypt = require("bcrypt");
const { isLoggedIn, isNotLoggedIn } = require("./middlewares");
const { User, Cycle } = require("../models");
const router = express.Router();
//회원가입
router.post("/api/auth/register", isNotLoggedIn, async (req, res) => {
const {
userName,
userEmail,
userPassword,
userBirth,
userWeight,
userHeight,
firCycleStart,
firCycleEnd,
meanCycle,
meanPeriod,
userAlcohol,
} = req.body;
try {
//exUser 존재 시
const exUser = await User.findOne({ where: { userEmail } });
if (exUser) {
return res.send("이미 가입된 이메일입니다");
}
//비밀번호 암호화
const hash = await bcrypt.hash(userPassword, 12);
//users 테이블에 사용자 정보 저장
await User.create({
userName: userName,
userEmail: userEmail,
userPassword: hash,
userBirth: userBirth,
userWeight: userWeight,
userHeight: userHeight,
meanCycle: meanCycle,
meanPeriod: meanPeriod,
userAlcohol: userAlcohol,
});
const loginUser = await User.findOne({
attributes: ["id"],
where: {
userEmail: userEmail,
},
});
//시작일 정보를 입력했을 때만 주기정보 저장
if (firCycleStart) {
await Cycle.create({
bleedStart: firCycleStart,
bleedEnd: firCycleEnd,
userId: loginUser.id,
});
}
return res.status(201).json({ completed: true });
} catch (error) {
console.error(error);
return next(error);
}
});
//로그인 성공 시 json 형식으로 사용자 이름 send
router.post("/api/auth/login", isNotLoggedIn, async (req, res, next) => {
passport.authenticate("local", (authError, user, info) => {
if (authError) {
console.log(authError);
return next(authError);
}
if (!user) {
return res.send(info.message);
}
return req.login(user, (loginError) => {
if (loginError) {
console.error(loginError);
return next(loginError);
}
return res.json({id: user.id, name: user.userName});
});
})(req, res, next);
});
//로그아웃
router.get("/api/auth/logout", isLoggedIn, async (req, res) => {
console.log(req.user.id);
req.logout();
req.session.destroy();
console.log("로그아웃");
return res.status(200).send("로그아웃 되었습니다");
});
module.exports = router;
<calendar.js>
const express = require("express");
const { isLoggedIn } = require("./middlewares");
const { User, Date, Cycle } = require("../models");
const router = express.Router();
const moment = require("moment");
const Sequelize = require("sequelize");
const Op = Sequelize.Op;
//캘린더 디테일 페이지 POST
//로그인한 사용자의 id는 req.user.id로 가져올 수 있다
router.post("/api/main/date", isLoggedIn, async (req, res) => {
const {
date,
cycleStart,
cycleEnd,
isSex,
isProtection,
isControl,
dateMood,
//★ 프런트 처리 미완 ★
dateCondition,
dateMemo,
} = req.body;
try {
//사용자가 입력한 정보를 dates 테이블에 입력
//upsert 기준이 (date+userId)여야하는데 sequelize는 FK를 composite key로 사용 불가... if문 쓰는 수 밖에?
const exDate = await Date.findOne({
where: { date: date, userId: req.user.id },
});
//이미 존재하던 날짜 정보면 update
if (exDate) {
await Date.update(
{
date: date,
isSex: isSex,
isProtection: isProtection,
isControl: isControl,
dateMood: dateMood,
dateCondition1: dateCondition,
//★ 프런트 처리 미완 ★
dateCondition2: 0,
dateCondition3: 0,
dateMemo: dateMemo,
userId: req.user.id,
},
{
where: { date: date, userId: req.user.id },
}
);
} else {
//새로운 날짜 정보면 create
await Date.create({
date: date,
isSex: isSex,
isProtection: isProtection,
isControl: isControl,
dateMood: dateMood,
dateCondition1: dateCondition,
//★ 프런트 처리 미완 ★
dateCondition2: 0,
dateCondition3: 0,
dateMemo: dateMemo,
userId: req.user.id,
});
}
//사용자가 입력한 정보를 cycles 테이블에 입력
//cycleStart cycleEnd 동시에 존재하는 경우는 없게 프런트에서 처리 완료
const exCycle = await Cycle.findOne({
where: {
bleedStart: { [Op.ne]: null },
bleedEnd: null,
userId: req.user.id,
},
});
//bleedStart만 있고 bleedEnd는 없는 이전 기록이 존재하는 경우
if (exCycle) {
if (cycleStart) {
//잘못된 입력. 이전 기록의 cycleEnd를 미리 설정해야 함.
res.send("최근 생리 종료일을 먼저 입력해야 합니다.");
} else if (cycleEnd) {
//사용자가 cycleEnd를 설정: cycles 테이블 bleedEnd 업데이트
await Cycle.update(
{
bleedEnd: cycleEnd,
},
{
where: {
bleedStart: { [Op.ne]: null },
bleedEnd: null,
userId: req.user.id,
},
}
);
return res.status(200).json({ completed: true });
}
} else {
//이전 기록이 존재하지 않는 경우
if (cycleStart) {
//사용자가 cycleStart를 설정: cycles 테이블 bleedStart 저장
await Cycle.create({
bleedStart: cycleStart,
userId: req.user.id,
});
return res.status(200).json({ completed: true });
} else if (cycleEnd) {
//사용자가 cycleEnd를 설정: cycles 테이블 bleedEnd 저장, bleedStart = bleedEnd - cycles.meanPeriod로 계산 후 저장
const userInfo = await User.findOne({
attributes: ["meanPeriod"],
where: { id: req.user.id },
});
await Cycle.create({
//★ meanPeriod를 입력 안 한 사용자일때? ★
bleedStart: moment(cycleEnd, "YYYY-MM-DD")
.subtract(userInfo.meanPeriod, "d")
.format("YYYY-MM-DD"),
bleedEnd: cycleEnd,
userId: req.user.id,
});
return res.status(200).json({ completed: true });
} else {
return res.status(200).json({ completed: true });
}
}
} catch (error) {
console.error(error);
return next(error);
}
});
//캘린더 디테일 페이지 GET
//입력된 정보가 있으면 보내주고, 없으면 "입력된 정보가 없습니다."
router.get("/api/main/", isLoggedIn, async (req, res) => {
//날짜는 req.body로 받아옴
const date = req.query.Date_send;
try {
const exDate = await Date.findOne({
where: { date: date, userId: req.user.id },
});
if (exDate) {
res.send(exDate);
} else {
res.send("입력된 정보가 없습니다.");
}
} catch (error) {
console.error(error);
return next(error);
}
});
router.get("/api/main/today", isLoggedIn, async (req, res) => {
//날짜는 req.body로 받아옴
const date = req.query.Today_send;
try {
const exDate = await Date.findOne({
where: { date: date, userId: req.user.id },
});
if (exDate) {
res.send(exDate);
} else {
res.send("입력된 정보가 없습니다.");
}
} catch (error) {
console.error(error);
return next(error);
}
});
module.exports = router;
login and register have no problem, but I couldn't use any functions needed login session or cookies. How I solve this problem?
Since the release of Google Chrome 80 on February 4, 2020, the default value of Cookie's SameSite property has been changed from None to Lax.
In other words, if you send an intersection request, not the same domain address, the cookie will not work.
The solution was to change the cookie settings to sameSite none in backend app.js.
But if you change it, you have to put the attribute secure true, and it was only possible in https.
Even if it is not https, if front and backend are using the same domain, there is no problem.
I believe that applying the domain will not result in an error, because eventually you have to have a domain to apply for https
I'm working in the final project from Udemy's Full Stack Web developer course, and I'm getting stuck at connecting my front and back-end. I'm getting a 404 when making a post request for sign in and I'm not sure why. Things I need to mention about the server.js:
There's no actual database, we're calling an array of objects within the same server.js file
I'm only trying to test with the first element of the array for now (in case you're wondering why am I using the database.user[0].
Now here's the server.js code:
const express = require('express');
const bcrypt = require('bcrypt-nodejs');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(cors());
const database = {
users: [
{
id: '123',
name: 'John',
email: 'john#gmail.com',
password: 'cookies',
entries: 0,
joined: new Date()
},
{
id: '124',
name: 'Sally',
email: 'sally#gmail.com',
password: 'bananas',
entries: 0,
joined: new Date()
}
]
}
app.get('/',(req, res)=>{
res.send(database.users);
});
app.post('/signin', (req, res) =>{
if(req.body.email === database.users[0].email &&
req.body.password === database.users[0].password){
res.json('success');
} else {
res.status(400).json('error logging in');
}
})
app.post('/register', (req, res) =>{
const { email, name, password } = req.body;
bcrypt.hash(password, null, null, function(err, hash) {
console.log(hash);
// Store hash in your password DB.
});
database.users.push({
id: '125',
name: name,
email: email,
password: password,
entries: 0,
joined: new Date()
})
res.json(database.users[database.users.length-1]);
})
app.get('/profile/:id', (req, res) => {
const { id } = req.params;
let found = false;
database.users.forEach(user => {
if(user.id === id) {
found = true;
return res.json(user);
}
})
if(!found){
res.status(400).json('not found');
}
})
app.post('/image', (req, res)=>{
const { id } = req.body;
let found = false;
database.users.forEach(user => {
if(user.id === id) {
found = true;
user.entries++;
return res.json(user.entries);
}
})
if(!found){
res.status(400).json('not found');
}
})
app.listen(3000, () => {
console.log('app is running on port 3000');
});
And here's my Signin.js component. I don't think you need to see the App.js file, since it only has route changes onSubmit. Also I'm not pasting the actual sign in form rendered in this Signin.js file to keep it simpler.
import React from 'react';
class Signin extends React.Component {
constructor(props){
super(props);
this.state={
signInEmail: '',
signInPassword: ''
}
}
onEmailChange = (event) => {
this.setState({signInEmail : event.target.value})
}
onPasswordChange = (event) => {
this.setState({signInPassword: event.target.value})
}
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
passworrd: this.state.signInPassword
})
})
this.props.onRouteChange('home');
}
So GET requests are working fine, the signin POST request throws a not found and I'm not sure why. I thought maybe a JSON parse issue, but I don't think that's the problem. Also, I'm running my front-end on por 3001 and my back-end on port 3000. I tried checking my server with Postman before attempting to connect the app with the server and it was working fine, but know it isn't! If I type the password incorrectly, I'm also getting a 404 instead of my 400 and console.log error. Maybe someone can shed some light here? Thanks!
I think you are missing these two things:-
Have you added body-parser in our app ?? (Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser)
const app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
I also notice in your Signin.js component(check the spelling of password)
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
passworrd: this.state.signInPassword // it should be password not passworrd
})
})
this.props.onRouteChange('home');
}