Hi everyone, I am facing an issue while trying to post data to my mongoDB from the frontend using React Hooks. The problem is that when I send the data instead of getting the all body I am only getting the id as response in my database. I don't know what I am missing in my code, I really need your help and I am open for all advices so I can better understand how to do. Here bellow are my codes:
CustomerPost:
import React, { useState } from "react";
import axios from "axios";
export default function CreateCustomer() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [phone, setPhone] = useState("");
const [passport, setPassport] = useState("");
const [booked, setBooked] = useState(false);
const onChangeName = (e) => {
setName({ name: e.target.value });
};
const onChangeEmail = (e) => {
setEmail({ email: e.target.value });
};
const onChangePhone = (e) => {
setPhone({ phone: e.target.value });
};
const onChangePassport = (e) => {
setPassport({ passport: e.target.value });
};
const onSubmit = (e) => {
e.preventDefault();
const bookingData = {
name: name,
email: email,
phone: phone,
passport: passport,
};
console.log(bookingData);
axios
.post("http://localhost:5000/customers", bookingData)
.then((res) => {
console.log(res.data);
setName(name);
setEmail(email);
setPhone(phone);
setPassport(passport);
})
.catch((error) => {
console.log(error);
});
setBooked(true);
};
return (
<div>
{booked ? (
<p className="bookedMsg">Your room was booked successfully!!!</p>
) : (
<form onSubmit={onSubmit} className="form contact-form">
<div className="input-group-wrap">
<div className="input-group">
<input
className="input"
type="text"
onChange={onChangeName}
placeholder="Name..."
required
/>
<span className="bar"></span>
</div>
<div className="input-group">
<input
className="input"
type="email"
onChange={onChangeEmail}
placeholder="Email..."
required
/>
<span className="bar"></span>
</div>
<div className="input-group">
<input
onChange={onChangePhone}
type="number"
className="input"
placeholder="Phone..."
required
/>
<span className="bar"></span>
</div>
<div className="input-group">
<input
onChange={onChangePassport}
type="number"
className="input"
placeholder="Passport..."
required
/>
<span className="bar"></span>
</div>
</div>
<button type="submit" className="btn form-btn btn-purple">
BOOK NOW
<span className="dots">
<i className="fas fa-ellipsis-h"></i>
</span>
</button>
</form>
)}
</div>
);
}
Customer.Route.js:
const Express = require("express");
var cors = require("cors");
const router = Express.Router();
const Controller = require("./Controller");
const data = require("./controller");
router.post("/", cors(), function (req, res) {
Controller.insertCustomer(req.body)
.then(function (data) {
res.status(data.status).send({ message: data });
})
.catch(function (err) {
res.status(data.status).send({ message: err.message });
});
});
router.get("/", cors(), function (req, res) {
Controller.searchAll()
.then((data) => {
res.status(data.status).send({ data: data.message });
})
.catch((err) => {
res.status(err.status).send({ message: err.message });
});
});
router.get("/:id", cors(), function (req, res) {
Controller.search(req.params.id)
.then((data) => {
res.status(data.status).send({ message: data.message });
})
.catch((err) => {
res.status(err.status).send({ message: err.message });
});
});
router.put("/:id", cors(), function (req, res) {
Controller.updateCustomer(req.params.id, req.body)
.then((data) => {
res.status(data.status).send({ message: data.message });
})
.catch((err) => {
res.status(err.status).send({ message: err.message });
});
});
router.delete("/:id", cors(), (req, res) => {
Controller.delete(req.params.id)
.then((data) => {
res.status(data.status).send({ message: data.message });
})
.catch((err) => {
res.status(err.status).send({ message: err.message });
});
});
module.exports = router;
dbConfig:
require("dotenv").config();
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const CustomerSchema = new Schema({
name: {
type: String,
require: true,
},
email: {
type: String,
require: false,
},
phone: {
type: Number,
require: true,
},
passport: {
type: Number,
require: true,
},
});
mongoose.connect(
process.env.DATABASE_URL,
{ useNewUrlParser: true, useUnifiedTopology: true },
(err) => {
if (err) {
console.log(err);
}
console.log("Connected to the mongodb");
}
);
module.exports = mongoose.model("Customer", CustomerSchema);
Controller.js:
const mongoose = require("../dbSchema/dbConfig");
const CustomerSchema = mongoose.model("Customer");
const Controller = function () {
this.insertCustomer = function (data) {
return new Promise(function (resolve, reject) {
var Customer = new CustomerSchema({
name: data.name,
email: data.email,
phone: data.phone,
passport: data.passport,
});
Customer.save()
.then(function () {
resolve({ status: 200, message: "Customer inserted Successfully" });
})
.catch(function (err) {
reject({ status: 500, message: "Error " + err });
});
});
};
this.updateCustomer = function (id, data) {
return new Promise((resolve, reject) => {
CustomerSchema.update({ _id: id }, data)
.then(() => {
resolve({ status: 200, message: "Customer updated Successfully" });
})
.catch(function (err) {
reject({ status: 500, message: err });
});
});
};
this.searchAll = function () {
return new Promise(function (resolve, reject) {
CustomerSchema.find()
.exec()
.then(function (data) {
resolve({ status: 200, message: data });
})
.catch(function (err) {
reject({ status: 500, message: err });
});
});
};
this.search = function (id) {
return new Promise(function (resolve, reject) {
CustomerSchema.find({ _id: id })
.exec()
.then(function (Customer) {
resolve({ status: 200, message: Customer });
})
.catch((err) => {
reject({ status: 500, message: err });
});
});
};
this.delete = function (id) {
return new Promise(function (resolve, reject) {
CustomerSchema.remove({ _id: id })
.then(() => {
resolve({ status: 200, message: "Customer Removed" });
})
.catch((err) => {
reject({ status: 500, message: err });
});
});
};
};
module.exports = new Controller();
Route.js:
const Express = require("express");
const Routes = Express.Router();
const CustomerRoute = require("../CustomerController/Customer.Route");
Routes.use("/customers", CustomerRoute);
module.exports = Routes;
It looks like you are sending an empty object from react, can you try adding async and await to your onSubmit function. I'm posting it as an answer to have more space for the code.
const onSubmit = async (e) => {
e.preventDefault();
const bookingData = {
name: name,
email: email,
phone: phone,
passport: passport,
};
console.log(bookingData);
await axios.post("/customers",
bookingData).then((res) => {
console.log(res.data);
setName(name);
setEmail(email);
setPhone(phone);
setPassport(passport);
}).catch((error) => {
console.log(error); });
setBooked(true);
};
Maybe you can modify your handleChange functions, something like this:
const onChangeName = (e) => {
setName(e.target.value)
}
I hope this works for you
Related
When trying to send an audio file to the backend using form data and then on the backend im using multer to parse the data and gridfs to send the data to mongoDB so it can handle a large audio file, im getting an error stating: audioData: ValidatorError: Path audioData is required. also, when i console.log(req.file.buffer) im getting undefined which is telling me my audioFile is not being sent to the backend
here is my App.js file
import React, { useState } from 'react';
const App = () => {
const [selectedFile, setSelectedFile] = useState(null);
const handleFileChange = (event) => {
setSelectedFile(event.target.files[0]);
}
const handleFormSubmit = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('audioFile', selectedFile);
fetch('http://localhost:4002/audio', {
method: 'POST',
body: formData
})
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Failed to upload audio file');
}
})
.then(data => {
console.log('File uploaded successfully:', data);
// Do something with the response data
})
.catch(error => {
console.error('Error uploading file:', error);
});
}
return (
<div className="flex h-[100vh] w-[100%] items-center justify-center">
<form onSubmit={handleFormSubmit}>
<input type="file" onChange={handleFileChange} />
<button type="submit" disabled={!selectedFile}>Upload</button>
</form>
</div>
);
};
export default App;
here is my server.js file
const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');
const { GridFsStorage } = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(cors());
mongoose.connect('mongodb+srv://jordandeeds31:<password>#cluster0.ibeioeb.mongodb.net/?retryWrites=true&w=majority', {
useUnifiedTopology: true,
useNewUrlParser: true,
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error(err);
});
const conn = mongoose.connection;
let gfs;
conn.once('open', () => {
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('audioFiles');
});
const storage = new GridFsStorage({
url: 'mongodb+srv://jordandeeds31:Jd400089#cluster0.ibeioeb.mongodb.net/grid?retryWrites=true&w=majority',
file: (req, file) => {
return {
filename: file.originalname,
bucketName: 'audioFiles'
};
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 90 * 1024 * 1024 // 10MB
},
fileFilter: (req, file, cb) => {
if (file.mimetype.startsWith('audio/')) {
cb(null, true);
} else {
cb(new Error('File type not supported.'));
}
}
});
const audioFileSchema = new mongoose.Schema({
fileUrl: {
type: String,
required: true
},
audioData: {
type: Buffer,
required: true
}
});
const AudioFile = mongoose.model('AudioFile', audioFileSchema);
app.post('/audio', upload.single('audioFile'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ message: 'No file uploaded.' });
}
console.log('req.file.buffer:', req.file.buffer);
const audioFile = new AudioFile({
fileUrl: `http://localhost:4002/audio/${req.file.filename}`,
audioData: req.file.buffer
});
const savedAudioFile = await audioFile.save();
res.json({ fileUrl: savedAudioFile.fileUrl });
} catch (err) {
console.error(err);
if (err instanceof multer.MulterError) {
res.status(400).json({ message: 'File upload error.' });
} else if (err.message === 'File type not supported.') {
res.status(400).json({ message: err.message });
} else {
res.status(500).send('Internal Server Error');
}
}
});
app.get('/audio/:filename', (req, res) => {
const { filename } = req.params;
const readStream = gfs.createReadStream({ filename });
readStream.on('error', (err) => {
console.error(err);
res.status(404).send('File not found.');
});
readStream.pipe(res);
});
app.listen(4002, () => {
console.log('Listening on port 4002');
});
This webpage is in a perpetual state of loading and I don't know why. It's almost as if it's awaiting the data. I tested the backend and the user exists and should be being sent but it's just waiting. I also tried isolating the the code so that it's just the bare minimum needed and there's still the perpetual loading. The This is what it looks like: Edit user Error Below is the code:
UserEditScreens.js
import axios from "axios";
import React, { useContext, useEffect, useReducer, useState } from "react";
import Container from "react-bootstrap/Container";
import Button from "react-bootstrap/Button";
import Form from "react-bootstrap/Form";
import { Helmet } from "react-helmet-async";
import { useNavigate, useParams } from "react-router-dom";
import { toast } from "react-toastify";
import LoadingBox from "../components/LoadingBox";
import MessageBox from "../components/MessageBox";
import { getError } from "../utils";
import { Store } from "./Store";
const reducer = (state, action) => {
switch (action.value) {
case "FETCH_REQUEST":
return { ...state, loading: true };
case "FETCH_SUCCESS":
return { ...state, loading: false };
case "FETCH_FAIL":
return { ...state, loading: false, error: action.payload };
case "UPDATE_REQUEST":
return { ...state, loadingUpdate: true };
case "UPDATE_SUCCESS":
return { ...state, loadingUpdate: false };
case "UPDATE_FAIL":
return { ...state, loadingUpdate: false };
default:
return state;
}
};
export default function UserEditScreen() {
const [{ loading, error, loadingUpdate }, dispatch] = useReducer(reducer, {
loading: true,
error: "",
});
const { state } = useContext(Store);
const { userInfo } = state;
const params = useParams();
const { id: userId } = params;
const navigate = useNavigate();
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [email, setEmail] = useState("");
const [isAdmin, setIsAdmin] = useState(false);
useEffect(() => {
const fetchData = async () => {
try {
dispatch({ type: "FETCH_REQUEST" });
const { data } = await axios.get(`/api/users/${userId}`, {
headers: { authorization: `Bearer ${userInfo.token}` },
});
dispatch({ type: "FETCH_SUCCESS", payload: data });
} catch (err) {
dispatch({ type: "FETCH_FAIL", payload: getError(err) });
}
};
fetchData();
}, [userInfo, userId]);
const submitHandler = async (e) => {
e.preventDefault();
try {
dispatch({ type: "UPDATE_REQUEST" });
await axios.put(
`/api/users/${userId}`,
{ _id: userId, firstName, lastName, email, isAdmin },
{ headers: { Authorization: `Bearer ${userInfo.token}` } }
);
dispatch({ type: "UPDATE_SUCCESS" });
toast.success("User updated successfully");
navigate("/admin/users");
} catch (error) {
toast.error(getError(error));
dispatch({ type: "UPDATE_FAIL" });
}
};
return (
<Container>
<Helmet>Edit User #{userId}</Helmet>
<h1>Edit User #{userId}</h1>
{loading ? (
<LoadingBox></LoadingBox>
) : error ? (
<MessageBox variant="danger">{error}</MessageBox>
) : (
<Form onSubmit={submitHandler}>
<Form.Group className="mb-3" controlId="firstName">
<Form.Label>First Name</Form.Label>
<Form.Control
value={firstName}
type="name"
onChange={(e) => setFirstName(e.target.value)}
required
></Form.Control>
</Form.Group>
<Form.Group>
<Form.Label>Last Name</Form.Label>
<Form.Control
value={lastName}
type="name"
onChange={(e) => setLastName(e.target.value)}
required
></Form.Control>
</Form.Group>
<Form.Group className="mb-3" controlId="lastName">
<Form.Label>Email</Form.Label>
<Form.Control
value={email}
type="email"
onChange={(e) => setEmail(e.target.value)}
required
></Form.Control>
</Form.Group>
<Form.Check
className="mb-3"
type="checkbox"
id="isAdmin"
label="isAdmin"
checked={isAdmin}
onChange={(e) => setIsAdmin(e.target.checked)}
></Form.Check>
<div>
<Button disabled={loadingUpdate} type="submit">
Update
</Button>
{loadingUpdate && <LoadingBox></LoadingBox>}
</div>
</Form>
)}
</Container>
);
}
UserRoutes.js
import express from "express";
import User from "../models/userModel.js";
import bcrypt from "bcryptjs";
import { generateToken, isAuth } from "../utils.js";
import expressAsyncHandler from "express-async-handler";
const userRouter = express.Router();
userRouter.get(
"/",
isAuth,
expressAsyncHandler(async (req, res) => {
const users = await User.find();
res.send(users);
})
);
userRouter.get(
"/:id",
isAuth,
expressAsyncHandler(async (req, res) => {
const user = await User.findById(req.params.id);
if (user) {
console.log(user);
res.send(user);
} else {
res.status(404).send({ message: "User Not Found" });
}
})
);
userRouter.put(
"/:id",
isAuth,
expressAsyncHandler(async (req, res) => {
if (user) {
const user = await User.findById(req.params.id);
user.firstName = req.body.firstName || user.firstName;
user.lastName = req.body.lastName || user.lastName;
user.email = req.body.email || user.email;
user.isAdmin = Boolean(req.body.isAdmin);
const updatedUser = await user.save();
res.send({ message: "User Updated", user: updatedUser });
} else {
res.status(404).send({ message: "User Not Found" });
}
})
);
userRouter.post(
"/signin",
expressAsyncHandler(async (req, res) => {
const user = await User.findOne({ email: req.body.email });
if (user) {
if (bcrypt.compareSync(req.body.password, user.password)) {
res.send({
_id: user._id,
name: user.firstName,
email: user.email,
token: generateToken(user),
});
return;
}
}
res.status(401).send({ message: "Invalid email or password" });
})
);
userRouter.post(
"/signup",
expressAsyncHandler(async (req, res) => {
const newUser = new User({
firstName: req.body.firstName,
lastName: req.body.firstName,
email: req.body.email,
password: bcrypt.hashSync(req.body.password),
});
const user = await newUser.save();
res.send({
_id: user._id,
firstName: user.firstName,
email: user.email,
isAdmin: user.isAdmin,
token: generateToken(user),
});
})
);
userRouter.put(
"/profile",
isAuth,
expressAsyncHandler(async (req, res) => {
const user = await User.findById(req.user._id);
if (user) {
user.name = req.body.name || user.name;
user.email = req.body.email || user.email;
if (req.body.password) {
user.password = bcrypt.hashSync(req.body.password, 8);
}
const updatedUser = await user.save();
res.send({
_id: updatedUser._id,
name: updatedUser.name,
email: updatedUser.email,
isAdmin: updatedUser.isAdmin,
token: generateToken(updatedUser),
});
} else {
res.status(404).send({ message: "User not found" });
}
})
);
export default userRouter;
I was struggling for several months to implement Cloudinary into a MERN web app, so I am running out of options to find the answer.
Basically, the problem here is that I don't have the knowledge to write successfully the necessary code to make it work.
Here is some insight:
I need to upload photos to Cloudinary for a Blog web page, (the problem is in the first two code files)
I was able to make it work for user's profilePics in the last two code files ( Settings.jsx & Settings.js ).. now I had to do almost the same,but that works for images in posts (Write.jsx & Posts.js ).
Feel free to ask for more info about
Front-End Write.jsx
import { useContext, useState } from "react";
import "./write.css";
import { Context } from "../../context/Context";
import { axiosInstance } from "../../config";
import { FcAddImage } from "react-icons/fc";
export default function Write() {
const [title, setTitle] = useState("");
const [desc, setDesc] = useState("");
const [file, setFile] = useState(null);
const [success, setSuccess] = useState(false);
const { user, dispatch } = useContext(Context);
const photo = user.photo;
console.log("post info", title, desc, file, user);
const handleSubmit = async (e) => {
e.preventDefault();
if (file) {
const data = new FormData();
data.append("id", user._id);
data.append("type", "file");
data.append("avatar", file);
try {
const res = await axiosInstance.post("/upload", "/posts", data);
setSuccess(true);
dispatch({ type: "UPDATE_SUCCESS", payload: res.data });
} catch (err) {
console.log(err);
dispatch({ type: "UPDATE_FAILURE" });
}
}
};
/*try {
await axiosInstance.post("/upload", data);
} catch (err) {}
}
try {
const res = await axiosInstance.post("/posts", newPost);
window.location.replace("/post/" + res.data._id);
} catch (err) {}*/
return (
<div className="write">
{file && (
<img
className="writeImg"
src={file ? URL.createObjectURL(file) : photo}
alt=""
/>
)}
<form className="writeForm" onSubmit={handleSubmit}>
<div className="writeFormGroup">
<label htmlFor="fileInput">
Image
<FcAddImage className="icon" />
</label>
<input
action="/:id"
method="POST"
type="file"
id="fileInput"
style={{ display: "none" }}
onChange={(e) => setFile(e.target.files[0])}
/>
<input
type="text"
placeholder="Title"
className="writeInput"
autoFocus={true}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div className="writeFormGroup">
<textarea
placeholder="Tell your story..."
type="text"
className="writeInput writeText"
onChange={(e) => setDesc(e.target.value)}
></textarea>
</div>
<button className="writeSubmit" type="submit">
Publish
</button>
{success && (
<span
style={{ color: "green", textAlign: "center", marginTop: "20px" }}
>
Post has been uploaded...
</span>
)}
</form>
</div>
);
}
Server-side Post.js
const User = require("../models/User");
const Post = require("../models/Post");
const cloudinary = require("../utils/cloudinary");
const upload = require("../utils/multer");
//UPLOAD FILE
router.post("/upload", upload.single("avatar"), async (req, res) => {
try {
// Upload image to cloudinary
const result = await cloudinary.uploader.upload(req.file.path);
//save changes
post.photo = result.secure_url;
res.status(200).json(savedPost);
} catch (err) {
res.status(500).json(err);
}
});
//CREATE POST
router.post("/", async (req, res) => {
const newPost = new Post(req.body);
try {
const savedPost = await newPost.save();
res.status(200).json(savedPost);
} catch (err) {
res.status(500).json(err);
}
});
//UPDATE POST
router.put("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (post.username === req.body.username) {
try {
const updatedPost = await Post.findByIdAndUpdate(
req.params.id,
{
$set: req.body,
},
{ new: true }
);
res.status(200).json(updatedPost);
} catch (err) {
res.status(500).json(err);
}
} else {
res.status(401).json("You can update only your post!");
}
} catch (err) {
res.status(500).json(err);
}
});
//DELETE POST
router.delete("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (post.username === req.body.username) {
try {
await post.delete();
res.status(200).json("Post has been deleted...");
} catch (err) {
res.status(500).json(err);
}
} else {
res.status(401).json("You can delete only your post!");
}
} catch (err) {
res.status(500).json(err);
}
});
//GET POST
router.get("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
res.status(200).json(post);
} catch (err) {
res.status(500).json(err);
}
});
//GET ALL POSTS
router.get("/", async (req, res) => {
const username = req.query.user;
const catName = req.query.cat;
try {
let posts;
if (username) {
posts = await Post.find({ username });
} else if (catName) {
posts = await Post.find({
categories: {
$in: [catName],
},
});
} else {
posts = await Post.find();
}
res.status(200).json(posts);
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;
Server-side Settings.js
//POST IMAGES
router.post("/upload", upload.single("avatar"), async (req, res) => {
console.log('/users/upload triggered')
try {
// Upload image to cloudinary
const result = await cloudinary.uploader.upload(req.file.path);
// Save user
User.findById(req.body.id, (err, user) => {
if (err) console.log(err)
user.profilePic = result.secure_url
user.save((err) => {
if (err) console.log(err)
res.json(user);
console.log('user saved')
})
});
} catch (err) {
console.log(err);
res.status(500).json(err);
}
});
I made conection to cloudinary changing the line
const res = await axiosInstance.post("/posts/upload", data);
but now, I can't post the 'posts', but is a step in the right direction
const handleSubmit = async (e) => {
e.preventDefault();
if (file) {
const data = new FormData();
data.append("id", user._id);
data.append("type", "file");
data.append("avatar", file);
try {
const res = await axiosInstance.post("/posts/upload", data);
setSuccess(true);
dispatch({ type: "UPDATE_SUCCESS", payload: res.data });
} catch (err) {
console.log(err);
dispatch({ type: "UPDATE_FAILURE" });
}
}
};
I am making a simple Walk-In register app where i will register a customer and then find that specific customer by their phone number. The registration part is done but i cannot get a customer by their phone number. A little help will be very much appreciated. Below im posting both my backend and frontend code.
API-Server.js
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const cors = require('cors')
const customerRouter = require('./routes/customer');
const app = express();
const port = process.env.PORT || 5000;
dotenv.config();
app.use(cors())
app.use(express.json());
app.use('/api/customer', customerRouter);
mongoose
.connect(process.env.MONGO_URI)
.then((data) => {
console.log(
'MongoDb connected successfully....'
);
})
.catch((err) => {
console.log(err);
});
app.listen(port, () => {
console.log(`Server is running at Port ${port}`);
});
API - customerRoute.js
const router = require('express').Router();
const Customer = require('../models/Customer');
router.post('/add', (req, res) => {
const newCustomer = new Customer({
name: req.body.name,
phone: req.body.phone,
address: req.body.address,
pin: req.body.pin,
});
newCustomer
.save()
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error creating a new customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/', (req, res) => {
Customer.find()
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/getbyphone', (req, res) => {
Customer.findOne({ phone: req.body.phone })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/getbyname', (req, res) => {
Customer.findOne({ name: req.body.name })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
module.exports = router;
Frontend - App.js
import { BrowserRouter as Router } from 'react-router-dom';
import { Route } from 'react-router-dom';
import Navbar from './components/Navbar';
import Search from './components/Search';
import Submit from './components/Submit';
function App() {
return (
<Router>
<div className='App'>
<Navbar />
<Route path='/' exact component={Submit} />
<Route path='/view' component={Search} />
</div>
</Router>
);
}
export default App;
frontend - search.js
import axios from 'axios';
import React, { Component } from 'react';
export default class Search extends Component {
constructor() {
super();
this.state = {
phone: '',
};
}
onPhoneChange = (event) => {
this.setState({
phone: event.target.value,
});
};
handleSubmit = (event) => {
event.preventDefault();
console.log(this.state.phone);
axios
.get(
'http://localhost:5000/api/customer/getbyphone',
this.state.phone
)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
this.setState({
phone: '',
});
};
render() {
return (
<div>
<h3>Search for a Customer</h3>
<form
onSubmit={this.handleSubmit}
className='form-control form-control-sm'>
<div className='form-group'>
<label>Phone: </label>
<input
type='text'
required
className='form-control'
onChange={this.onPhoneChange}
value={this.state.phone}
/>
</div>
<div className='form-group'>
<input
type='submit'
className='btn btn-primary'
value='Search Customer'
/>
</div>
</form>
</div>
);
}
}
you could change this route and read phone number from params
router.get('/getbyphone/:phone', (req, res) => {
Customer.findOne({ phone: req.params.phone }) // change this line
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
and change the react part like this
handleSubmit = (event) => {
event.preventDefault();
console.log(this.state.phone);
axios
.get(
'http://localhost:5000/api/customer/getbyphone'+this.state.phone /// change this line
)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
this.setState({
phone: '',
});
};
I have created the backend operations using Node.js / MongoDB and created services for them, but when I run the server it indicates that I've connected successfully, but I can't see a database in Robo 3T.
Here is what I coded:
DBConfig.js
var mongoose = require ('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name : {
type : String,
require : true
},
address : {
type : String,
require : true
}
});
mongoose.model("User", UserSchema);
module.exports = mongoose;
mongoose.connect('mongodb://127.0.0.1:27017/TestDB4', function(err){
if(err)
{
console.log(err);
process.exit(-1);
}
console.log("Connected to the db")
});
I can't see an error. Why isn't the DB created?
check your User.Controller.js as this below,
var mongoose = require('../DBSchema/SchemaMapper');
var UserSchema = mongoose.model('User');
var UserController = function(){
this.insert = (data) => {
return new Promise((resolve, reject) => {
var user = new UserSchema({
userName: data.userName,
password: data.password
});
user.save().then(() => {
resolve({status: 200, message: "Added new user"});
}).catch(err => {
reject({status: 500, message: "Error:- "+err});
})
})
}
this.update = (id, data) => {
return new Promise((resolve, reject) => {
UserSchema.update({_id: id}, data).then(() => {
resolve({status: 200, message: "update user"});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.searchAll = () => {
return new Promise((resolve, reject) => {
UserSchema.find().exec().then((data) => {
resolve({status: 200, data: data});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.search = (id) => {
return new Promise((resolve, reject) => {
UserSchema.find({_id:id}).exec().then(user => {
resolve({status: 200, data: user});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.delete = (id) => {
return new Promise((resolve, reject) => {
UserSchema.remove({_id:id}).then(() => {
resolve({status: 200, message: "remove user"});
}).catch(err => {
reject({status: 500, message:"Error:- " + err});
})
})
}
}
module.exports = new UserController();
And User.Route.js as below,
var express = require('express');
var router = express.Router();
var Controller = require('./User.Controller');
router.post('/', (req, res) => {
Controller.insert(req.body).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
});
router.put('/:id', (req, res) => {
Controller.update(req.params.id, req.body).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
});
router.get('/', (req, res) => {
Controller.searchAll().then(data => {
res.status(data.status).send({data: data.data});
}).catch(err => {
res.status(err.status).send({message: err.message});
});
});
router.get('/:id', (req, res) => {
Controller.search(req.params.id).then(data => {
res.status(data.status).send({data: data.data});
}).catch(err => {
res.status(err.status).send({message: err.message});
});
});
router.delete('/:id', (req, res) => {
Controller.delete(req.params.id).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
})
module.exports = router;
check your app.js as follows
const Express = require("express");
const BodyParser = require("body-parser");
const Routes = require("./Routes");
const Cors = require("cors");
const app = Express();
app.use(Cors());
app.use(BodyParser.urlencoded({ extended: false }));
app.use(BodyParser.json());
app.use('/', Routes);
app.listen(8083, 'localhost', (err) => {
if(err) {
console.log(err);
process.exit(-1);
}
console.log("Server listen port 8083");
});
and Routes.js as follows,
var Express = require("express");
var Routes = Express.Router();
var UserRoute = require('./src/User/User.Route');
var CommentRoute = require('./src/Comment/Comment.Route');
Routes.use('/user/', UserRoute);
Routes.use('/comment/', CommentRoute);
module.exports = Routes;