When I use fetch my .then code isn't working - javascript

So I am trying to redirect after I am deleting the page, it get's deleted from the database but it doesn't redirect me to my homepage. It worked fine when I was using json-server locally, but when I started using Mongoose it wasn't working properly and wasn't redirecting.
The code inside .then isn't working, I tried console.log inside the .then but it didn't log
I am using mongoose as my database
Here is my entire component:
import { useParams } from "react-router-dom";
import useFetch from "../useFetch";
import { useHistory } from "react-router-dom";
import moment from "moment";
import profile_image from "../images/picture.jpg";
const BlogDetails = () => {
let blogDate = moment().format('D MMM YYYY');
const { id } = useParams();
const { data: blog, isPending, errorMsg } = useFetch("http://localhost:5000/postsdata/" + id);
const history = useHistory()
const handleDelete = () => {
fetch('http://localhost:5000/postsdata/' + blog._id, { method: 'DELETE' })
.then(() => {
history.push('/');
})
.catch((err) => console.log(err))
}
return (
<div className="blog-details">
<div className="top-profile">
<div className="top-profile-picture">
<img src={profile_image} alt="profile-pic-top" />
</div>
<div className="top-profile-name">
<p>Vishwajeet Deshmukh</p>
</div>
</div>
{isPending && <div>Loading...</div>}
{errorMsg && <div>{errorMsg}</div>}
{blog && (
<article className="blog-main-content" >
<div className="main-content-header">
<div className="content-title-date">
<h2 className="blogdetails-title">{blog.title}</h2>
<p className="blogdetails-date">{blogDate}</p>
</div>
<div className="content-image">
<img src={blog.imgsrc} alt="" />
</div>
</div>
<div className="blogdetails-body"><p>{`${blog.postBody}`}</p></div>
<button className="blogdetails-delete" onClick={handleDelete}>Delete Me</button>
</article>
)}
</div>
);
};
export default BlogDetails;
Here is my router.js which handles my delete
const express = require('express');
const router = express.Router();
const { Posts } = require("./models");
//<----------------------------------- CRUD OPERATIONS ------------------------------------------>
router.get("/", () => {
console.log("Server Connected");
})
//<---------------------------- Get Posts from Database ---------------------------->
router.get("/postsdata", (req, res) => {
Posts.find((err, data) => {
if (err) {
res.status(500).send(err);
} else {
res.status(201).send(data);
}
return null;
})
})
//<------------- Get Specific Posts from Database --------------->
router.get("/postsdata/:_id", (req, res) => {
const id = req.params._id;
Posts.findById(id, (err, data) => {
if (err) {
res.status(500).send(err);
throw new Error(err)
} else {
res.status(201).send(data);
}
return data;
})
})
//<---------------------------- Post On the Posts Database ---------------------------->
router.post("/postsdata", (req, res) => {
const db = req.body;
Posts.create(db, err => {
if (!err) {
console.log("Posted on Server");
} else {
throw new Error(err)
}
return null
})
})
//<---------------------------- Delete Posts from Database ---------------------------->
router.delete("/postsdata/:id", (req, res) => {
const id = req.params._id
Posts.deleteOne(id, (err, data) => {
if (err) {
console.log(err);
throw new Error(err)
} else {
console.log(data);
}
return null
})
})
module.exports = router;

after deleting the postdata, send a response from the API.
router.delete("/postsdata/:id", (req, res) => {
const id = req.params._id
Posts.deleteOne(id, (err, data) => {
if (err) {
console.log(err);
throw new Error(err)
} else {
return res.status(200).json({status: 'success'}); // try with this
}
return null
})
})

Hello try it with async/await sayntax
const handleDelete = async () => {
await fetch('http://localhost:5000/postsdata/' + blog._id, { method: 'DELETE' });
history.push('/');
}

Related

function is not running completly instead moving to other function

In my route
router.get("/", verifyAdmin, getUsers);
It should first verify admin then move to the getUsers function.
but instead it is moving towards getUsers function.
Routes:
import express from "express";
import {
updateUser,
deleteUser,
getUser,
getUsers,
} from "../controllers/user.js";
import { verifyAdmin, verifyUser,verifyToken } from "../middlewares/verifytoken.js";
const router = express.Router();
//UPDATE
router.put("/:id", verifyUser, updateUser);
//DELETE
router.delete("/:id", verifyUser, deleteUser);
//GET
router.get("/:id", verifyUser, getUser);
//GET ALL
router.get("/", verifyAdmin, getUsers); // Problem is occouring here
export default router;
Middlewares:
import jwt from "jsonwebtoken";
const JWT_KEY = "jwt"; // for development its here only
export const verifyToken = (req,res,next) => {
const token = req.cookies.access_token;
if(!token) return res.status(404).json("You are not authenticated");
jwt.verify(token,JWT_KEY,(err,user)=>{
if(err) return res.status(403).json("Token is invalid");
req.user =user;
next();
})
};
export const verifyUser = (req, res,next) => {
verifyToken(req, res, next,()=>{ // This section is not working
if(req.user._id === req.params.id || req.user.isAdmin){
next();
}else{
return next(res.status(403).json("You are not allowed to access this."));
}
})
}
export const verifyAdmin = (req, res,next) => {
verifyToken(req,res,next,() => {
if (req.user.isAdmin) {
return next();
} else {
return res.status(403).json("you are not admin");
}
});
};
User controllers:
import User from "../models/User.js";
//Update User
export const updateUser = async(req,res) =>{
try {
const updatedUser = await User.findByIdAndUpdate(req.params.id,{$set:req.body},{new:true});
res.status(200).json(updatedUser);
} catch (error) {
return res.status(500).json(error);
}
}
//Delete User
export const deleteUser = async(req,res) =>{
try {
await User.findByIdAndDelete(req.params.id);
return res.status(200).json("User has been deleted");
} catch (error) {
return res.status(500).json(error);
}
}
// getUser
export const getUser = async(req,res) =>{
try {
const user = await User.findById(req.params.id);
return res.status(200).json(user);
} catch (error) {
return res.status(500).json(error);
}
}
// Get All Users
export const getUsers = async(req,res) =>{
try {
const users = await User.find();
return res.status(200).json(users);
} catch (error) {
return res.status(500).json(error);
}
}

JsonWebTokenError: jwt must be a string, node.js

I'm getting the error JsonWebTokenError: jwt must be a string when getting the jwt from the front end (react.js) and using in middleware to verify the token. If I tried to use toString it gives me another error JsonWebTokenError: jwt malformed.
Update
As soon as i pass the accessToken from frontEnd it converted into object in the AuthMiddleware.js. I'm passing middleware on header in file Post.js(attached below)
AuthMiddleware.js
const { verify } = require("jsonwebtoken")
const validateToken = (res, req, next) => {
const accesToken = req.header("accesToken");
const stringAccesToken = accesToken.toString()
console.log(typeof (stringAccesToken), "accesToken type")
if (!stringAccesToken) {
return res.json({ error: "user not logged in" })
}
try {
const validToken = verify(stringAccesToken, "importantSecret");
console.log(validToken, 'validtoken')
if (validToken) {
return next();
}
} catch (err) {
console.log(err, "error")
}
}
module.exports = { validateToken }
User.js (backend for login)
const express = require("express");
const router = express.Router()
const { Users } = require("../models")
const bcrypt = require("bcrypt")
const { sign } = require("jsonwebtoken")
router.post("/login", async (req, res) => {
const { username, password } = req.body;
const user = await Users.findOne({ where: { username: username } });
if (!user) {
return res.json({ error: "User dosen't exist" })
}
bcrypt.compare(password, user.password)
.then((match) => {
if (!match) {
return res.json({ error: "Wrong Username and Password match" })
}
const accessToken = sign({ username: user.username, id: user.id }, "importantSecret")
res.json(accessToken)
})
})
module.exports = router;
Post.js
import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom';
import axios from 'axios';
import './Post.css'
function Post() {
let { id } = useParams();
const [postObject, setPostObject] = useState({})
const [comments, setComments] = useState([]);
const [newComment, setNewComment] = useState("");
// console.log(comments)
const addComment = () => {
const accessToken = sessionStorage.getItem('accessToken')
console.log(typeof (accessToken), 'acces token in comment button')
axios.post(`http://localhost:4000/comments`,
{
commentBody: newComment,
PostId: id
},
{
headers: {
accessToken: sessionStorage.getItem("accessToken"),
}
}
)
.then((res) => {
// console.log(res)
const data = res.data;
console.log(data, 'comments')
setComments([...comments, data])
setNewComment("")
})
.catch((err) => {
alert(err, 'Error:comment')
})
}
useEffect(() => {
axios.get(`http://localhost:4000/posts/byId/${id}`)
.then((res) => {
// console.log(res)
const data = res.data;
// console.log(data)
setPostObject(data)
// setPost(data)
})
// comment api request
axios.get(`http://localhost:4000/comments/${id}`)
.then((res) => {
// console.log(res)
const data = res.data;
// console.log(data)
setComments(data)
})
}, [])
return (
<div className='Post'>
<div className='left__side'>
<div className='left__side__wrapper'>
<div className='title'>{postObject.title}</div>
<div className='text'>{postObject.postText}</div>
<div className='username'>{postObject.username}</div>
</div>
</div>
<div className='right__side'>
<div className='right__side__wrapper'>
<div className='add__comment__container'>
<input type="text"
value={newComment}
placeholder="Comment"
// autoComplete="off"
onChange={(e) => setNewComment(e.target.value)}
/>
<button onClick={addComment}> Submit Comment</button>
</div>
<div className='listOfCommnets'>
{comments.map((item, index) => {
{/* console.log(item, 'item') */ }
return <div className='comments' key={index}>Comments:<br />{item.commentBody}</div>
})}
</div>
</div>
</div>
</div>
)
}
export default Post
Because the jwt token is using an object as an input rather than using the word "verify," it won't work with the object in which you are receiving the error any longer. Instead, you must attempt as follows.
var jwt = require("jsonwebtoken");
const validateToken = (res, req, next) => {
const accesToken = req.header("accesToken");
const stringAccesToken = accesToken;
if (!stringAccesToken) {
return res.json({ error: "user not logged in" });
}
jwt.verify(stringAccesToken, "importantSecret", function (err, decoded) {
if (err)
return console.log(err)
// Next Code
next();
});
};
module.exports = { validateToken };
I found the solution:
As the error said JWT need to be string,
I first tried using accesToken.toString() that gives [object object],
On second try i used JSON.stringy and that was also unsuccessful.
Final scuccesful attemp was to use library name - flatted (to convert json to string and after using it i just used split till i did'nt get the token).
faltted (link) - https://github.com/WebReflection/flatted#flatted
Worked Solution -
AuthMiddleware.js
const { parse, stringify, toJSON, fromJSON } = require('flatted');
const validateToken = (res, req, next) => {
const authToken = req.header("accessToken");
const string = stringify(authToken)
const token = string && string.split(' ')[2];
const tokenPure = token.split('"')[4]
if (!tokenPure) {
return res.json({ error: "user not logged in" })
}
try {
const validToken = verify(tokenPure, "importantSecret");
// console.log(validToken, 'validtoken')
if (validToken) {
return next();
}
} catch (err) {
console.log(err, "error")
}
}
module.exports = { validateToken }

why does my result always return as false

I'm using mern to set up a social media of sorts. I'm trying to do if a post is favourited then it should be true if not false. However the result for favourited is always false regardless of if the post is in the users likes in the DB.
If the post has been favourited the button is meant to be set to show the word removed, that way the user knows they've favourited it. If its not favourited(false) it should show add. However, if the user favourites a post and likes it then refreshes the page instead of showing remove it shows add and if the user adds it again it then adds the same movie to the DB.
favourite routes
const express = require('express');
const router = express.Router();
const { authJwt } = require("../middlewares");
const Favourite = require("../models/favourite.model");
router.use(function(req, res, next) {
res.header(
"Access-Control-Allow-Headers",
"x-access-token, Origin, Content-Type, Accept"
);
next();
});
router.post("/favouriteNumber", [authJwt.verifyToken], (req, res) => {
Favourite.find({"movieId": req.body.movieId})
.exec((err, favourite) => {
if(err) return res.status(400).send(err)
res.status(200).json({success: true, favouriteNumber: favourite.length})
})
})
router.post("/favourited", [authJwt.verifyToken], (req, res) => {
Favourite.find({"movieId": req.body.movieId, "userFrom": req.body.userFrom})
.exec((err, favourite) => {
if(err) return res.status(400).send(err)
let result = false;
if(favourite.length !== 0) {
result = true
}
res.status(200).json({success: true, favourited: result});
})
})
router.post("/addToFavourite", [authJwt.verifyToken], (req, res) => {
const favourite = new Favourite(req.body)
favourite.save((err, doc) => {
if(err) return res.json({success: false, err})
return res.status(200).json({success: true, doc})
})
})
router.post("/removeFavorite", [authJwt.verifyToken], (req, res) => {
Favourite.findOneAndDelete({movieId: req.body.movieId, userFrom: req.body.userFrom})
.exec((err, doc) => {
if(err) return res.json({success: false, err})
return res.status(200).json({success: true, doc})
})
})
router.post("/getFavourites", [authJwt.verifyToken], (req, res) => {
Favourite.find({ userFrom: req.body.data })
.populate('userFrom')
.exec((err, films) => {
if(err) return res.status(400).send(err)
res.status(200).json({success: true, films})
})
})
module.exports = router;
favourite component
import Axios from 'axios';
import React, { useEffect, useState } from 'react'
import styled from "styled-components";
import authService from '../../services/auth.service';
import authHeader from '../../services/auth-header';
const FavouriteButton = styled.button`
height: 30px;
width: 40px;
`;
function FavouriteComp(props) {
const currentUser = authService.getCurrentUser();
const [favourited, setFavourited] = useState(false);
const variable = {
userFrom: currentUser.id,
movieId: props.movieInfo?.id,
movieTitle: props.movieInfo?.title,
movieImg: props.movieInfo?.poster_path
}
const onClickFavourite = () => {
//if user already likes the film - remove it
if(favourited) {
Axios.post('http://localhost:8080/api/favourite/removeFavorite', variable, { headers: authHeader() })
.then(response =>{
if(response.data.success){
setFavourited(!favourited)
console.log("Removed from favourites")
}else {
alert('Failed to remove');
}
})
//if not - add to favourites
}else {
Axios.post('http://localhost:8080/api/favourite/addToFavourite', variable, { headers: authHeader() })
.then(response =>{
if(response.data.success){
setFavourited(!favourited)
console.log("Added to favourites")
}else {
alert('Failed to add');
}
})
}
}
useEffect(() => {
Axios.post('http://localhost:8080/api/favourite/favourited', variable, { headers: authHeader() })
.then(response =>{
if(response.data.success){
// setFavourited(response.data.favourited)
// console.log(response.data)
}else {
alert('Failed to get info');
}
})
}, [])
return (
<div>
<FavouriteButton onClick={onClickFavourite}>{!favourited ? "add" : "remove"}</FavouriteButton>
</div>
)
}
export default FavouriteComp

I'm struggling with setting up an express + react crud app, can anyone give me insight to this CRUD app?

Here is the backend code for the app.js (express.js)
const express = require( 'express' );
const cors = require ( 'cors' );
const morgan = require ('morgan' );
const fs = require( 'fs' );
const dataPath = './data.json'
const PORT = 3000
//init express
const app = express();
//App middelwear
app.use(express.urlencoded({ extended: true}))
app.use(express.json())
app.use(cors());
app.use(morgan( 'tiny' ));
app.checkout('api', (req, res) => {
fs.readFile(dataPath, 'utf8', (err, data) => {
if (err) {
throw err;
}
res.send(JSON.parse(data));
})
})
//Get
app.get('/api', (req, res) => {
const { title } = req.body;
fs.readFile(dataPath, 'utf8', (err, data) => {
if (err) {
throw err;
}
const dataArray = JSON.parse(data)
const newItem = {
id: dataArray.length + 1,
title
}
dataArray.push(newItem)
fs.writeFile(dataPath, JSON.stringify(dataArray), 'utf8', (err, data) => {
if (err) {
throw err
}
res.send(dataArray)
})
})
})
//Post
app.post('/add', (req, res) => {
const { title } = req.body;
fs.readFile(dataPath, 'utf8', (err, data) => {
if (err) {
throw err;
}
const dataArray = JSON.parse(data)
const newItem = {
id: dataArray.length + 1,
title
}
dataArray.push(newItem)
fs.writeFile(dataPath, JSON.stringify(dataArray), 'utf8', (err, data) => {
if (err) {
throw err
}
res.send(dataArray)
})
})
})
app.put('/edit', (req, res) => {
const { id } = req.params
const { title, description, URL } = req.body
fs.readFile(dataPath, 'utf8', (err, data) => {
if (err) {
throw err
}
let dataArray = JSON.parse(data)
let updateDataArray = []
const newItem = {
id,
title,
description,
URL
}
dataArray.forEach(oldItem => {
if(oldItem.id == id) {
updateDataArray.push(newItem);
}else {
updateDataArray.push(oldItem);
}
})
dataArray = updateDataArray
fs.writeFile(dataPath, JSON. stringify(dataArray), 'utf8', (err, data) => {
if(err) {
throw err;
}
res.send(dataArray)
})
})
})
app.delete('/api/:id', (req, res) => {
const { id } = req.params
fs.readFile(dataPath, 'utf8', (err, data) => {
if (err) {
throw err;
}
})
})
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
Here is the add.js code, it is the file that would add the crud's information to the display.js page:
Frontend component/Add.js
import React from 'react';
import Button from 'react-bootstrap/Button';
// The Add component should be visible when the display componentn is loaded.
class Add_Component extends React.Component {
constructor(props) {
super(props);
this.handleAddIDChange = this.handleAddIDChange.bind(this);
this.handleAddTitleChange =this.handleAddTitleChange.bind(this);
this.handleAddDescriptionChange = this.handleAddDescriptionChange.bind(this);
this.handleAddURLChange = this.handleAddURLChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state={
error:null,
addID:null,
addTitle: "",
addDescription: "",
addURL: ""
};
}
// After input is submitted the state will change of AddID.
handleAddIDChange(event) {
this.setState({addID:event.target.value})
}
// After input is submitted the state of AddTitle will change.
handleAddTitleChange(event) {
this.setState({addName:event.target.value})
}
handleAddDescriptionChange(event) {
this.setState({addDescription:event.target.value})
}
// After the input is submitted the state of AddURL will change.
handleAddURLChange(event) {
this.setState({addURL:event.target.value})
}
handleSubmit(event) {
event.preventDefault();
fetch("/add", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
addID:this.state.addID,
addTitle: this.state.addTitle,
addDescription:this.state.addDescription,
addURL:this.state.addURL
})
})
.then(res => {
res.json()
alert('Entry has been added to the database')
window.location.reload()
})
.then(result => {
window.location.reload()
})
.catch(error => console.log(error))
}
// Return the Web Projects to display it on the screen.
render() {
return(
<div className="ProjectAddForm">
<form id="formAddEntry" onSubmit={this.handleSubmit}>
<h1>Add Project</h1>
<label>Add an unique ID for your new Project entry</label><br/>
<input type="text" placeholder="Example ID: 7" onChange={this.handleAddIDChange} name="addID" id="addID"></input><br/>
<label>Add an unique Title for your new Project entry</label><br/>
<input type="text" placeholder="Example Title: Web Project One" onChange={this.handleAddTitleChange} name="addtitle" id="addID"></input><br/>
<label>Add an unique ID for your new Project entry</label><br/>
<input type="text" placeholder="Example Description: Project using javascript" onChange={this.handleAddIDChange} name="addTitle" id="addTitle"></input><br/>
<label>Add an unique URL for your new Project entry</label><br/>
<input type="text" placeholder="Example URL: www.crudsystem.com" onChange={this.handleAddDescriptionChange} name="addDescription" id="addDescription"></input><br/>
<Button variant="dark" type="submit">Add Project Entry</Button>
</form>
</div>
)
}
}
export default Add_Component;
Here is the display page in the frontend called Display.js
component/Display.js
import React from 'react';
/*The display Component will be called once the submit user
Component is achieved in input. The state is set to null initially.
*/
class Display extends React.Component {
constructor(props) {
super(props);
this.state = {
error:null,
projects: []
};
}
//The data.json file is used for this project it is fetched from the url.
componentDidMount() {
fetch("/api")
.then(res => res.json())
.then(project => this.setState({projects: project}, () => console.log(`User fetched ...`, project)))
.catch(error => {
console.log('Error:', error)
this.setState({error})
});
}
//Render and return, this will be the jsx that will display the projects.\
render() {
return(
<div className="div-Frame">
<h1>Web Projects</h1>
<ul className="projectList">
{this.state.projects.map(project =>
<li key={project.id}>
<h2>Project {project.id}</h2>
<strong>ID:</strong> {project.id} <br/>
<strong>Project Title:</strong> {project.title} <br/>
<strong>Description:</strong> {project.description} <br/>
<strong>URL:</strong> {project.URL}</li>
)}
</ul>
</div>
)
}}
export default Display;
I'm trying to create a crud app for school, but so far the data.json only adds a new id, any help would be appreciated, here is the data.json file
backend,
datad.json
[{"id":1,"title":"Memory Game!","description":"Memory game created using Create React app.","URL":"https://protected-badlands-68828.herokuapp.com/"},{"id":2,"title":"Online store","description":"Online store created with HTML, CSS and JavaScript.","URL":"https://github.com/eriancoet/Capstone/tree/master"},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9}]
as you can see the crud only loads more id's...help please.

Send a message from Server side to React front (NodeJS)

Im currently trying to send a message from my server side and display it in my react front end.
I have tried everything to display the message I use with res.send() but the react fails to receive it can anyone help me point out what I am doing wrong here?
Sample of the front end:
import React, {Component} from 'react';
import axios from 'axios';
import Tabs from 'react-bootstrap/Tabs';
import Tab from 'react-bootstrap/Tab';
export default class CreateFile extends Component {
constructor(props) {
super(props);
this.onChangeFileDescription = this.onChangeFileDescription.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
file_description: '',
};
this.handleSelect = this.handleSelect.bind(this);
axios
.get("http://localhost:4000/api/isloggedin")
.then(res => {
if (!res.data) {
return this.setState({isloggedin: false});
}
});
}
onChangeFileDescription(e) {
this.setState({
file_description: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
console.log(`Form submitted:`);
console.log(`File Description: ${this.state.file_description}`);
const newFile = {
file_description: this.state.file_description,
}
axios.post('http://localhost:4000/files/add', newFile)
.then(res => console.log(res.data));
this.setState({
file_description: '',
})
}
render() {
return this.state.isloggedin ? (
<div style={{marginTop: 20}}>
<h3>Upload a New File</h3>
<Tabs
id="controlled-tab-example"
activeKey={this.state.key}
onSelect={key => this.setState({key})}
>
<Tab eventKey="audio" title="Audio">
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>File Description: </label>
<input type="text"
className="form-control"
value={this.state.file_description}
onChange={this.onChangeFileDescription}
/>
</div>
</Tabs>
</div>
) : (
<h3>Please login</h3>
);
}
}
This is the server side:
Im checking if the submitted form is empty and if it is sending a error back asking users to fill the required field.
const express = require('express');
const bodyParser = require('body-parser');
const fileRoutes = express.Router();
const File = require("../models/fileHandler");
module.exports = function(app) {
app.use(bodyParser.json());
fileRoutes.route('/').get(function (req, res) {
File.find(function (err, files) {
if (err) {
console.log(err);
} else {
res.json(files);
}
});
});
fileRoutes.route('/:id').get(function (req, res) {
let id = req.params.id;
File.findById(id, function (err, file) {
res.json(file);
});
});
fileRoutes.route('/add').post(function (req, res) {
console.log(req.body.file_description);
if (req.body.file_description === ""){
console.log("its empty!");
var result = {"data" :"hello everybody !"}
res.status(200).json({'description': 'description is needed'});
return res.send(result);
}
let file = new File(req.body);
file.save()
.then(file => {
res.status(200).json({'file': 'file added successfully'});
})
.catch(err => {
res.status(400).send('adding new file failed');
});
});
fileRoutes.route('/update/:id').post(function (req, res) {
File.findById(req.params.id, function (err, file) {
if (!file)
res.status(404).send('data is not found');
else
file.file_description = req.body.file_description;
file.file_size = req.body.file_size;
file.file_duration = req.body.file_duration;
file.file_artist = req.body.file_artist;
file.file_bitrate = req.body.file_bitrate;
file.file_codec = req.body.file_codec;
file.file_audioChannels = req.body.file_audioChannels;
file.file_dimensions = req.body.file_dimensions;
file.file_tag = req.body.file_tag;
file.file_colorProfile = req.body.file_colorProfile;
file.file_extension = req.body.file_extension;
file.file_employeeResponsible = req.body.file_employeeResponsible;
file.file_editActive = req.body.file_editActive;
file.file_completed = req.body.file_completed;
file.save().then(file => {
res.json('File updated');
})
.catch(err => {
res.status(400).send("Update not possible");
});
});
});
app.use('/files', fileRoutes);
};
Ok after some digging I managed to solve this issue.
I thought i posted here in case anyone had a similar problem.
So what I did was to check everything with express validator and if there was any problem to send it to the react front end.
And in react front end if the there is any problem received regarding that specific field it will display it on top of the input field.
hope this helps.
{this.state.errors &&
this.state.errors.file_description && <p>{this.state.errors.file_description.msg}
And the complete snippet of the react front end.
import React, {Component} from 'react';
import axios from 'axios';
import Tabs from 'react-bootstrap/Tabs';
import Tab from 'react-bootstrap/Tab';
export default class CreateFile extends Component {
constructor(props) {
super(props);
this.onChangeFileDescription = this.onChangeFileDescription.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
file_description: ''
};
this.handleSelect = this.handleSelect.bind(this);
axios
.get("http://localhost:4000/api/isloggedin")
.then(res => {
if (!res.data) {
return this.setState({isloggedin: false});
}
});
}
onChangeFileDescription(e) {
this.setState({
file_description: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
console.log(`Form submitted:`);
console.log(`File Description: ${this.state.file_description}`);
const newFile = {
file_description: this.state.file_description
}
axios.post('http://localhost:4000/files/add', newFile)
.then(result => {
if (result.data.errors) {
return this.setState(result.data);
}
return this.setState({
userdata: result.data,
errors: null,
success: true
});
});
this.setState({
file_description: ''
})
}
render() {
return this.state.isloggedin ? (
<div style={{marginTop: 20}}>
<h3>Upload a New File</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>File Description: </label>
<input type="text"
className="form-control"
value={this.state.file_description}
onChange={this.onChangeFileDescription}/>
{this.state.errors &&
this.state.errors.file_description && <p>{this.state.errors.file_description.msg}</p>}
</div>
<label className="form-check-label">Yes</label>
</div>
</div>
<div className="form-group">
<input type="submit" value="Upload File" className="btn btn-primary"/>
</div>
</form>
</Tab>
</Tabs>
</div>
) : (
<h3>Please login</h3>
);
}
}
for the backend I have also tweaked it so if there is any problem it will post that back to the react front end validating with Express validator and using the normal route and post methods.
const express = require('express');
var { check, validationResult } = require("express-validator/check");
const bodyParser = require('body-parser');
const fileRoutes = express.Router();
const File = require("../models/fileHandler");
module.exports = function(app) {
const fileValidation = [
check("file_description")
.not()
.isEmpty()
.withMessage("Description required"),
];
app.use(bodyParser.json());
fileRoutes.route('/').get(function (req, res) {
File.find(function (err, files) {
if (err) {
console.log(err);
} else {
res.json(files);
}
});
});
fileRoutes.route('/:id').get(function (req, res) {
let id = req.params.id;
File.findById(id, function (err, file) {
res.json(file);
});
});
fileRoutes.route('/add').post(fileValidation, function (req, res) {
var errors = validationResult(req);
if (!errors.isEmpty()) {
return res.send({ errors: errors.mapped() });
}else{
console.log("its empty!");
let file = new File(req.body);
file.save()
.then(file => {
res.status(200).json({'file': 'file added successfully'});
})
.catch(err => res.send(err));
}
});
fileRoutes.route('/update/:id').post(function (req, res) {
File.findById(req.params.id, function (err, file) {
if (!file)
res.status(404).send('data is not found');
else
file.file_description = req.body.file_description;
file.save().then(file => {
res.json('File updated');
})
.catch(err => {
res.status(400).send("Update not possible");
});
});
});
app.use('/files', fileRoutes);
};

Categories