Trying to push register data to db but server returns error 500 (Internal Server Error), I am just training so dont know how to fix it here's my code. The browser that the problem is in query hook or route path but i cant find it
const express = require('express')
const config = require('config')
const mongoose = require('mongoose')
const app = express()
const PORT = config.get('port') || 5000
app.use(express.json({extended:true}))
app.use('/api/auth', require('./routes/auth.routes'))
async function start(){
try{
await mongoose.connect(config.get("mongoURL"),{
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true,
})
app.listen(PORT, () => console.log(`app has been started on port ${PORT}...`))
}catch(e){
console.log('server Error', e.message)
process.exit(1)
}
}
start()
this is my route (routes/auth.routes.js) Route should validate achieved data and save indo db. Validation working, but if i make real user it returns err 500
const {Router} = require('express')
const User = require('../models/User')
const bcrypt = require('bcryptjs')
const config = require('config')
const {check, validationResult} = require('express-validator')
const router = Router()
router.post(
'/register',
[
check('email', 'incorrect email').isEmail(),
check('password', 'min 6 symb')
.isLength({min:6})
],
async(req,res) => {
try{
const errors = validationResult(req)
if(!errors.isEmpty()){
return res.status(400).json({
errors:errors.array(),
message:'incorrect data'
})
}
const {email, password} = req.body
console.log(req)
const candidate = await User.findOne({email})
if(candidate){
return res.status(400).json({message:'Already exists'})
}
const hashedPassword = await bcrypt.hash(password, 12)
const user = new User({email, password: hashedPassword})
await user.save()
res.status(201).json({message:'created'})
} catch(e){
res.status(500).json({message:'something goes wrong try again'})
}
})
module.exports = router
config file maybe needs i dont know
{
"port":5000,
"jwtSecret":"secret",
"mongoUri":"mongourl/myFirstDatabase?retryWrites=true&w=majority"
}
hook that should push data to server
import {useCallback, useState} from 'react'
export const useHttp = () => {
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const request = useCallback( async(url,method = "GET", body=null, headers={}) => {
setLoading(true)
try{
if(body){
body = JSON.stringify(body)
headers['Content-Type'] = 'application/json'
}
const response = await fetch( url, {method, body,headers} )
const data = await response.json()
if(!response.ok){
throw new Error(data.message ||'something goes wrong')
}
setLoading(false)
return data
} catch (e) {
setLoading(false)
setError(e.message)
throw e
}
},[])
const clearError = useCallback(()=>setError(null),[])
return {loading, request, error, clearError}
}
and page where it all must works
import {useEffect, useState} from 'react'
import { useHttp } from '../hooks/http.hook'
import { useMessage } from '../hooks/message.hook'
const AuthPage = () => {
const {loading,error, request, clearError} = useHttp()
const [form, setForm] = useState({})
const message = useMessage()
const handleChange = (e) => {
setForm({...form, [e.target.name]:[e.target.value] })
}
useEffect(()=>{
message(error)
clearError()
}, [error])
const registerSubmit = async()=>{
try{
const data = await request('/api/auth/register', 'POST', {...form})
console.log('Data',data)
}catch(e) {
}
}
return(
<>
<div className="input-field ">
<input onChange={handleChange}name="email" placeholder="put email" id="email" type="text" />
<label htmlFor="email">Email</label>
</div>
<div className="input-field ">
<input onChange={handleChange} name="password"placeholder="put password" id="password" type="text" />
<label htmlFor="password">password</label>
</div>
<button onClick={registerSubmit} disabled={loading} className='btn black'>Register</button>
</>
)
}
Node server returns error
Error: Illegal arguments: object, number
[0] at _async (/Users/user/first-nodeapp/node_modules/bcryptjs/dist/bcrypt.js:214:46)
[0] at /Users/user/first-nodeapp/node_modules/bcryptjs/dist/bcrypt.js:223:17
[0] at new Promise (<anonymous>)
[0] at Object.bcrypt.hash (/Users/user/first-nodeapp/node_modules/bcryptjs/dist/bcrypt.js:222:20)
[0] at /Users/user/first-nodeapp/routes/auth.routes.js:33:45
[0] at processTicksAndRejections (internal/process/task_queues.js:93:5)
Related
I watched video tutorials on youtube. https://youtu.be/0aPLk2e2Z3g and I got problems and http://localhost:3003/auth/register 500 (Internal Server Error) problem I don't know if this is the same problem or not.
I'm trying to change the proxy localhost to 127.0.0.1
I think my problem is with registering past
I stuck with this problem for 5 hours.
this is my controller auth.js
import { db } from "../db.js";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
export const register = (req, res) => {
//CHECK EXISTING USER
const q = "SELECT * FROM users WHERE email = ? OR username = ?";
db.query(q, [req.body.email, req.body.username], (err, data) => {
if (err) return res.status(500).json(err);
if (data.length) return res.status(409).json("User already exists!");
//Hash the password and create a user
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(req.body.password, salt);
const q = "INSERT INTO users(`username`,`email`,`password`) VALUES (?)";
const values = [req.body.username, req.body.email, hash];
db.query(q, [values], (err, data) => {
if (err) return res.status(500).json(err);
return res.status(200).json("User has been created.");
});
});
};
export const login = (req, res) => {
//CHECK USER
const q = "SELECT * FROM users WHERE username = ?";
db.query(q, [req.body.username], (err, data) => {
if (err) return res.status(550).json(err);
if (data.length === 0) return res.status(404).json("User not found!");
//Check password
const isPasswordCorrect = bcrypt.compareSync(
req.body.password,
data[0].password
);
if (!isPasswordCorrect)
return res.status(400).json("Wrong username or password!");
const token = jwt.sign({ id: data[0].id }, "jwtkey");
const { password, ...other } = data[0];
res
.cookie("access_token", token, {
httpOnly: true,
})
.status(200)
.json(other);
});
};
export const logout = (req, res) => {
res.clearCookie("access_token",{
sameSite:"none",
secure:true
}).status(200).json("User has been logged out.")
};
and register.jsx
import React from "react";
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";
const Register = () => {
const [inputs, setInputs] = useState({
username: "",
email: "",
password: "",
});
const [err, setError] = useState(null);
const navigate = useNavigate();
const handleChange = (e) => {
setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value }));
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post(`/auth/register`, inputs);
navigate("/login");
} catch (err) {
setError(err.response.data);
}
};
return (
<div className="auth">
<h1>Register</h1>
<form>
<input
required
type="text"
placeholder="username"
name="username"
onChange={handleChange}
/>
<input
required
type="email"
placeholder="email"
name="email"
onChange={handleChange}
/>
<input
required
type="password"
placeholder="password"
name="password"
onChange={handleChange}
/>
<button onClick={handleSubmit}>Register</button>
{err && <p>{err}</p>}
<span>
Do you have an account? <Link to="/login">Login</Link>
</span>
</form>
</div>
);
};
export default Register;
my localhost
"proxy": "http://localhost:8800/api/"
I'm making a face Sign up and see if your data is saved. But it has this problem. I've tried checking both video clips and looking for solutions from other sources but still can't help.
I have a react component "Signin.js", I have some login input fields in it, I am trying to create a login system using nodejs, expressjs and MySQL. To do this, I have created a post request, that sends the data of my input fields to nodejs backend where the data is passed into the database to check if the login credentials are correct or not. If the credentials are found in the database, the global variable auth in my backend "index.js" becomes true, I am sending that variable from nodejs to reactjs using a get request. if auth is true, I should get redirected to the next page other wise it says, login failed.
The problem is that when I enter the correct credentials, in the first 2 clicks, I get login failed, but in the 3rd click, it redirects me to the next page.
Here is my react component Signin.js
import React, {useState , useEffect} from 'react';
import Navbar from './Navbar';
import './signin.css';
import {Link} from 'react-router-dom';
import axios, { Axios } from 'axios';
function Signin()
{
const [userId, setUserId] = useState("");
const [password, setPassword] = useState("");
const [accessCode, setAccessCode] = useState("");
const [auth , setAuth] = useState(false);
const receiveauthentication = () => {
console.log("Calling authentication function");
axios.get("http://localhost:3001/api/get/signin2").then((response) => {
setAuth(response.data);
console.log(response.data);
if(auth === true)
{
console.log(response.data);
setAuth(false);
document.location.href = "http://localhost:3000/Dashhome";
}
else{
alert('Incorrect Login/Password');
}
})
};
const signInInfoSent = () => {
axios.post("http://localhost:3001/api/get/signin", {userId:userId, password:password}).then(() => {
console.log("Successfully Login");
}).then(receiveauthentication());
}
return(
<>
<Navbar/>
<div id="signUp">
<div id="form">
<label htmlFor = "userId">User ID</label>
<input type="textbox" id="userId" placeholder = "Username" onChange={(e) =>{
setUserId(e.target.value);
}}/>
<label htmlFor = "password">Password</label>
<input type="password" id="password" placeholder = "Password" onChange={(e) =>{
setPassword(e.target.value);
}}/>
<label htmlFor = "otp">Access Code</label>
<input type="textbox" id="otp" placeholder = "OTP" onChange={(e) =>{
setAccessCode(e.target.value);
}}/>
<button onClick={()=>{ signInInfoSent() }}>Sign in</button>
</div>
</div>
</>
);
}
export default Signin;
Here is my nodejs backend index.js
const express = require('express')
const app = express()
const mySql = require('mysql');
const cors = require('cors')
const bodyParser = require('body-parser')
const db = mySql.createPool({
host:"127.0.0.1",
user:"root",
password:"password",
database:"kotekdatabase"
})
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.json())
app.use(cors())
let auth;
var userIdG;
var trade_data = {};
app.post("/api/get/signin", (req,res)=>{
const userid = req.body.userId;
userIdG = userid;
const password = req.body.password;
const sqlSelect =
`SELECT * FROM signup WHERE userid = ? AND password = ?`;
db.query(sqlSelect,[userid , password], (err, result)=> {
//console.log(err);
if(result != null)
{
//res.send(result);
console.log("Successfully Login");
auth = true;
}
else
{
console.log("UnSuccessfully Login");
auth = false;
}
})
})
app.get("/api/get/retrieveStrategies" , (req , res)=>{
const q = 'SELECT * FROM strategy WHERE userid = ?';
db.query(q , [userIdG] , (err , result)=>{
if(err)
{
console.log(err);
}
else{
console.log(result[0]);
res.send(result);
}
});
})
app.get("/api/get/signin2", (req,res) =>{
console.log(auth);
res.send(auth);
auth = false;
})
var strategyG;
app.post("/api/get/strategy", (req,res)=>{
console.log("Strategy Name received\n");
const str = req.body.strategy;
strategyG = str;
console.log(strategyG);
})
var signupAuth = 0;
app.post("/api/insert", (req,res)=>{
const userid = req.body.userId;
const password = req.body.password;
const consumerKey = req.body.consumerKey;
const consumerSecret = req.body.consumerSecret;
const accessToken = req.body.accessToken;
const sqlInsert = "INSERT INTO signup (userid, password, consumerKey, consumerSecret, accessToken) VALUES (?,?,?,?,?);"
db.query(sqlInsert, [userid, password, consumerKey, consumerSecret, accessToken], (err, result)=> {
if(err){
console.log(err);
signupAuth = 0;
console.log(signupAuth);
}
else {
signupAuth = 1;
console.log(signupAuth);
}
})
})
app.post("/api/tradeinfo", (req,res)=>{
console.log("Inserting fo user Id,Strategy:", userIdG,strategyG);
const userid = userIdG;
const Sno = strategyG;
const indexName = req.body.indexName;
const Sprice = req.body.Sprice;
const SLP = req.body.SLP;
const PE = req.body.PE;
const Exitt = req.body.Exit;
const TType = req.body.TType;
const SL = req.body.SL;
const CE = req.body.CE;
const Entry = req.body.Entry;
const sqlInsert = "INSERT INTO strategy (userid, Sname, indexName, strikePrice, SLP, PE, Exitt, tradeType, SL, CE, Entry) VALUES (?,?,?,?,?,?,?,?,?,?,?);"
db.query(sqlInsert, [userid, Sno, indexName, Sprice, SLP, PE, Exitt, TType, SL, CE, Entry], (err, result)=> {
//console.log(err);
console.log(err);
})
})
app.post("/api/get/strategysent", (req,res)=>{
const userid = userIdG;
const Sno = strategyG;
const indexName = req.body.indexName;
const Sprice = req.body.Sprice;
const SLP = req.body.SLP;
const PE = req.body.PE;
const Exitt = req.body.Exit;
const TType = req.body.TType;
const SL = req.body.SL;
const CE = req.body.CE;
const Entry = req.body.Entry;
const sqlSelect =
`SELECT userid FROM signup WHERE userid = ${userid} AND password = ${password} AND consumerKey = ${consumerKey}`;
db.query(sqlSelect, (err, result)=> {
//console.log(err);
if(result != null)
{
//res.send(result);
console.log("Successfully Login");
auth = true;
}
else
{
console.log("UnSuccessfully Login");
auth = false;
}
})
})
app.post("/api/get/trade_data" , (req,res)=>{
res.send(req.body);
console.log(req.body);
trade_data = req.body;
})
app.get("/api/send/trade_data" , (req , res)=>{
res.send(trade_data);
} )
app.listen(3001, () => {
console.log("running on port 3001");
})
You have a floating promise, receiveauthentication is called too soon, you need to call it within the first .then handler.
Try this:
axios.post("http://localhost:3001/api/get/signin", {userId:userId, password:password}).then(() => {
console.log("Successfully Login");
receiveauthentication();
edit
you can merge the signin to remove extra axios request, i.e. return auth on the first request, and wrap state checking within useEffect, as it's a side effect:
server:
app.post("/api/get/signin", (req,res)=>{
const userid = req.body.userId;
userIdG = userid;
const password = req.body.password;
const sqlSelect =
`SELECT * FROM signup WHERE userid = ? AND password = ?`;
db.query(sqlSelect,[userid , password], (err, result)=> {
//console.log(err);
if(result != null)
{
//res.send(result);
console.log("Successfully Login");
auth = true;
}
else
{
console.log("UnSuccessfully Login");
auth = false;
}
res.send(auth);
})
})
client
// set 0 to skip on first render
const [auth, setAuth] = useState(0);
const signInInfoSent = () => {
axios.post("http://localhost:3001/api/get/signin", {
userId: userId,
password: password
}).then((response) => {
console.log("Successfully Login");
setAuth(response.data);
}).catch(err => console.error(err));
}
useEffect(() => {
console.log('check auth', auth);
if (auth === true) {
document.location.href = "http://localhost:3000/Dashhome";
} else if (auth === false) {
alert('Incorrect Login/Password');
}
}, [auth]);
I was creating a book library management CRUD and I am Using React v18.
I am struggling to add data to my mongdb atlas because whenever I pass formData to axios.post via Redux, I'm always getting empty req.body on the backend controller.
This however does not occur when I am using postman when adding data to my database via form-data. My login form which also using axios.post works fine and the booklist using axios.get also works fine, the crud for book is the only one that is not working.
This is my bookCreate.js:
const BookCreate = () => {
const [title, setTitle] = useState('')
const [responsibility, setResponsibility] = useState('')
const [uniform_title, setUniform_title] = useState('')
const [parallel_title, setParallel_title] = useState('')
const [main_author, setMain_author] = useState('')
const [other_author, setOther_author] = useState('')
const [contributors, setContributors] = useState('')
const [corp_author, setCorp_author] = useState('')
const [placePub, setPlacePub] = useState('')
const [publisher, setPublisher] = useState('')
const [yearPub, setYearPub] = useState('')
...
const submitHandler = (e) => {
e.preventDefault();
const formData = new FormData();
formData.set('title', title);
formData.set('responsibility', responsibility);
formData.set('uniform_title', uniform_title);
formData.set('parallel_title', parallel_title);
formData.set('main_author', main_author);
formData.set('other_author', other_author);
formData.set('contributors', contributors);
formData.set('corp_author', corp_author);
formData.set('placePub', placePub);
formData.set('publisher', publisher);
formData.set('yearPub', yearPub);
dispatch(newBooks(formData))
}
return (
<Fragment>
<MetaData title={'TUP-T Online Library - Admin'} />
{/*<div className="row">*/}
<SideNavbarAdmin/>
<div></div>
<div className="dashboard-content">
<div className="dashboard-page">
<div className="dashboard-header">
<h1>Add Book</h1>
</div>
<div className="dashboard-body">
<form className="" onSubmit={submitHandler} encType='multipart/form-data'>
<div className="row g-3">
<div className="col md-6">
<div className="form-group">
<label htmlFor="title_field">Title</label>
<input
type="text"
id="title_field"
className="form-control"
name='title'
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
...
}
This is bookAction.js:
export const newBooks = (bookData) => async (dispatch) => {
try {
dispatch({ type: NEW_BOOK_REQUEST })
const config = {
headers: {
"Content-Type": "multipart/form-data"
// "Content-Type": "application/json"
}
}
// for(var pair of bookData.entries()) {
// console.log(pair[0]+ ', '+ pair[1]);
// }
const { data } = await axios.post('/api/v1/book/new', bookData, config)
dispatch({
type: NEW_BOOK_SUCCESS,
payload: data
})
} catch (error) {
dispatch({
type: NEW_BOOK_FAIL,
payload: error.response.data.message
})
}
}
This is bookController.js:
exports.createBook = async (req, res, next) => {
console.log(req.body);
}
My app.js on the backend:
const express = require("express");
const app = express();
const cookieParser = require("cookie-parser");
const errorMiddleware = require("./middlewares/errors");
app.use(express.json());
app.use(cookieParser());
app.use(errorMiddleware);
app.use(express.urlencoded({ extended: true }));
const book = require("./routes/book");
const auth = require("./routes/auth");
app.use("/api/v1", book);
app.use("/api/v1", auth);
app.use(errorMiddleware);
module.exports = app;
FormData send multipart/form-data, hence the parsers you used in app.js won't work. The common and easy way is to use multer. First install it:
npm install --save multer
Then where you hade urlencoded, and cookieParser use this:
const multer = require('multer');
const upload = multer();
app.use(upload.none())
I'm using this upload.none() because you seem to be not sending any file. If you are, you can visit the above link, mutter will let you do that.
Also you can simplify submitHandler since each form input has a name by getting ride of all those states and simply give the form to FormData() as parameter with e.target:
const submitHandler = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
dispatch(newBooks(formData));
};
I'm using ReactJS to build a blog app. I can use axios get, put, delete but NOT POST. Every time I post a new blog, it gives me server responded with a status of 500 (Internal Server Error).
I have been struggle with this issue for a week and couldn't figure out the reason. Thank you very much for your help! Let me know if you need additional information.
Here are my codes:
API
import axios from 'axios'
const baseUrl = `/api/blogs`
let token = null
const setToken = newToken => {
token = `bearer ${newToken}`
}
const getAll = () => {
const request = axios.get(baseUrl)
return request.then(response => response.data)
}
const create = async newBlog => {
const config = {headers: { Authorization: token }}
const response = await axios.post(baseUrl, newBlog, config)
return response.data
}
const update = async (id, newObject) => {
const request = axios.put(`${baseUrl}/${id}`, newObject)
const response = await request
return response.data
}
const remove= async (id) => {
const config = {headers: { Authorization: token }}
const request = axios.delete(`${baseUrl}/${id}`, config)
const response = await request
return response.data
}
const exportedObject = { getAll, create, update, setToken, remove }
export default exportedObject
Frontend App.js
import React, { useState, useEffect, useRef } from 'react'
import blogService from './services/blogs'
import loginService from './services/login'
import Blog from './components/Blog'
import LoginForm from './components/LoginForm'
import BlogForm from './components/BlogForm'
import Togglable from './components/Togglable'
import Notification from './components/Notification'
import axios from 'axios'
const App = () => {
const [blogs, setBlogs] = useState([])
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [user, setUser] = useState(null)
const [loginVisible, setLoginVisible] = useState(false)
const [notificationText, setNotificationText] = useState("")
const [notificationStyle, setNotificationStyle] = useState("notification")
const [Toggle, setToggle] = useState(false)
const BlogFormRef = useRef()
useEffect(() => {
const Data = async () => {
const initialBlogs = await blogService.getAll()
setBlogs( initialBlogs )
}
Data()
}, [])
useEffect(() => {
const loggedUserJSON = window.localStorage.getItem('loggedBlogUser')
if (loggedUserJSON) {
const user = JSON.parse(loggedUserJSON)
setUser(user)
blogService.setToken(user.token)
}
}, [])
const addBlog = async (blogObject) => {
BlogFormRef.current.toggleVisibility()
if (blogObject.title !== '' && blogObject.author !== '' && blogObject.url !== '') {
const newBlog = await blogService.create(blogObject)
setBlogs(blogs.concat(newBlog))
setNotificationStyle('notification')
setNotificationText(`A new blog ${blogObject.title} by ${blogObject.author} is added`)
setToggle(!Toggle)
setTimeout(() => {
setToggle(false)
}, 5000)
setBlogs('')
console.log(blogObject)
document.location.reload()
} else {
setNotificationStyle('Warning')
setNotificationText('You must fill all fields to create a blog')
setToggle(!Toggle)
setTimeout(() => {
setToggle(false)
}, 5000)
}
}
Backend
const blogsRouter = require('express').Router()
const Blog = require('../models/blog')
const User = require('../models/user')
const jwt = require('jsonwebtoken')
const middleware = require("../utils/middleware")
blogsRouter.get('/', async (request, response) => {
const blogs = await Blog.find({}).populate('user', { username: 1, name: 1 })
response.json(blogs)
})
blogsRouter.get('/:id', (request, response) => {
Blog.findById(request.params.id)
.then(blog => {
if (blog) {
response.json(blog)
} else {
response.status(404).end()
}
})
})
blogsRouter.post('/', middleware.userExtractor, async (request, response) => {
const body = request.body
const user = request.user
const decodedToken = jwt.verify(request.token, process.env.SECRET)
if (!decodedToken.id){
return response.status(401).json({error: 'token missing or invalid'})
}
if(body.title === undefined){
return response.status(400).send({
error: 'title is missing'
})
}
else if(body.author === undefined){
return response.status(400).send({
error: 'author is missing'
})
}
else if(body.url === undefined){
return response.status(400).send({
error: 'url is missing'
})
}
else{
const blog = new Blog({
title: body.title,
author: body.author,
url: body.url,
likes: body.likes,
user: user.id
})
const savedBlog = await blog.save()
//console.log(savedBlog)
//console.log(user)
user.blogs = user.blogs.concat(savedBlog.id)
await user.save()
const populatedBlog = await savedBlog.populate('user', { username: 1, name: 1 }).execPopulate()
response.status(200).json(populatedBlog.toJSON())
}
})
blogsRouter.delete('/:id', middleware.userExtractor, async (request, response) => {
const blog = await Blog.findByIdAndRemove(request.params.id)
const user = request.user
const decodedToken = jwt.verify(request.token, process.env.SECRET)
if(! request.token || !decodedToken.id){
return response.status(401).json({error:'token is missing or invalid'})
}
else if(blog.user.toString() === user.id.toString()){
await Blog.findByIdAndRemove(request.params.id)
response.status(204).end()
}
else{
return response.status(401).json({error:'cannot process deletion'})
}
})
blogsRouter.put('/:id', async (request, response) => {
const body = request.body
const blog = {
title: body.title,
author:body.author,
url: body.url,
likes: body.likes
}
await Blog.findByIdAndUpdate(request.params.id, blog, { new: true })
.then(updatedBlog => {
response.json(updatedBlog)
})
})
module.exports = blogsRouter
Mongoose
const mongoose = require('mongoose')
const blogSchema = new mongoose.Schema({
title: {type:String,
required: true},
author:{type:String,
required: true},
url: {type:String,
required: true},
likes: {type:Number,
default: 0},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'}
})
blogSchema.set('toJSON', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString()
delete returnedObject._id
delete returnedObject.__v
}
})
const Blog = mongoose.model('Blog', blogSchema)
module.exports = Blog
Additional information: terminate output, the info is actually POST just cannot render in the front
terminal output
I'm using react/express/SQL
I have a simple program where user can enter data, view data and update their data. inserting and getting data from my SQL database works fine, but when I try to update data from my database I get the following error.
Error when trying to update data
TypeError: Cannot read property 'userEvent' of undefined
index.js
const express = require('express'); // node js frontend/backend lib
const app = express()
const mysql = require('mysql'); // DB
const cors = require('cors') //By default requests from any other origins will be restricted by the browser. We have two differnet local hosts, so by default wont be able we req res data
//Setting up SQL, hide password properly
const db = mysql.createConnection({
host:'localhost',
user: 'root',
password: '*****',
database: 'calendardb',
});
app.use(cors());
app.use(express.json()); // turns data into json
// insert information in to DB
app.post('/send',(req,res) =>{
const userEvent = req.body.userEvent
db.query('INSERT INTO calevent (userEvent) VALUES (?)',
userEvent, (err,result) =>{
if(err){
console.log(err)
} else{
res.send("Data send to DB")
}
}
);
});
//Getting data from DB
app.get("/getData",(req, res) =>{
db.query("SELECT * FROM calevent", (err, result) => {
if(err){
console.log(err)
}else{
res.send(result)
}
});
});
//Update data
app.put('/update', (res,req) => {
//const newUserEvent = "test";
//const id = 325;
const newUserEvent = req.body.userEvent;
const id = req.body.id;
db.query("UPDATE calevent SET userEvent = ? WHERE id = ?", [newUserEvent, id],(err, result) => {
if(err){
console.log(err)
}else{
console.log(result)
}
});
});
app.listen(3001, () =>{
console.log('bonger');
});
The problem is that it is unable to get the variables from the front end and access it in the backend. if I uncomment the following: //const newUserEvent = "test"; //const id = 325; and use that as my hardcoded user input, everything works fine, I can update my database.
app.js
import React from 'react';
import { useState,useEffect } from "react";
import Calendar from 'react-calendar';
import 'react-calendar/dist/Calendar.css';
import Axios from 'axios';
const CalendarApp = () => {
var [selectedDate, newDate] = useState(new Date());
const [event, newEvent] = useState("")
const [userEvent, setUserEvent] = useState("")
const [items, setItem] = useState([])
const [userEventList, setUserEventList] = useState([])
const [newUserEvent, setNewUserEvent] = useState("")
//Add event to DB
const addUserEvent = () => {
Axios.post("http://localhost:3001/send", {userEvent: userEvent,
}).then(() => {
console.log("Data sent to DB")
setUserEventList([...userEventList,{userEvent: userEvent,}])
});
};
//Gets data from DB
const getUserEvent = () =>{
Axios.get("http://localhost:3001/getData").then((response) => {
setUserEventList(response.data)
});
};
//Updates data chosen by user
const updateUserEvent = (id) => {
console.log(newUserEvent, id)
Axios.put('http://localhost:3001/update', {newUserEvent:newUserEvent, id: id}).then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
};
return(
<div id="eventList">
<h2>Event List</h2>
<div className="List">
{userEventList.map((val,key) => {
return (
<div>
Event: {val.userEvent}, Key: {val.id}
<div>
<input type="text" placeholder="Edit" onChange={(event) => {
setNewUserEvent(event.target.value)
}}/>
<button onClick={() => {updateUserEvent(val.id)}}>Update</button>
</div>
</div>
)
})}
</div>
</div>
)
the code console.log(newUserEvent, id) returns the correct updated user input and id number but for some reason when using axios.put it does not send it to the back end to be used there.