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" });
}
}
};
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');
});
I'm creating new app(e-commerce) using react and react-redux with axios. For back-end using Mongo-DB(MERN stack).
There is no problem when saving data to database, but when i get that data from database middleware can not reach token from headers. But postman work fine both get and save data.
I use the same middleware when saving data to database, it work fine. But when i try to fetch data from database i get unauthorized error.
here is my code.
FOR BACK-END;
Server file;
import express from "express";
import connectDB from "./config/db.js";
import dotenv from "dotenv";
import colors from "colors";
import productRoutes from "./routes/productRoutes.js";
import userRouters from "./routes/userRoutes.js";
import shippingAddressRoutes from "./routes/shippingAddressRoutes.js";
import { notFound, errorHandler } from "./middleware/errorMiddleware.js";
dotenv.config();
connectDB();
const app = express();
// body parser
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// API route
app.get("/", (req, res) => {
res.send("API is running....");
});
// route for products
app.use("/api/products", productRoutes);
// route for users
app.use("/api/users", userRouters);
// route for shipping address
app.use("/api/shippingaddress", shippingAddressRoutes);
app.use(notFound);
app.use(errorHandler);
const PORT = process.env.PORT || 5000;
app.listen(
PORT,
console.log(
`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold
)
);
shippingAddressRoute file;
import express from "express";
import {
saveAddress,
changeAddress,
getAddress,
} from "../controllers/shippingAddressController.js";
import protect from "../middleware/authMiddleware.js";
const router = express.Router();
router
.route("/")
.get(protect, getAddress)
.post(protect, saveAddress)
.put(protect, changeAddress);
export default router;
shippingAddressController file;
import asyncHandler from "express-async-handler";
import ShippingAddress from "../models/shippingAddressModel.js";
import User from "../models/userModel.js";
// #desc get address
// #route GET /api/shippingaddress
// #access Private
const getAddress = asyncHandler(async (req, res) => {
const user = User.findById(req.user._id);
if (user) {
const { email } = req.body;
const shippingAddress = await ShippingAddress.findOne({
userEmail: email,
});
if (shippingAddress) {
res.status(200);
res.json({
address: shippingAddress.address,
city: shippingAddress.city,
postalCode: shippingAddress.postalCode,
county: shippingAddress.country,
email: shippingAddress.userEmail,
});
} else {
res.status(404);
throw new Error("Address not found");
}
} else {
res.status(404);
throw new Error("User not found");
}
});
// #desc save address
// #route POST /api/shippingaddress
// #access Private
const saveAddress = asyncHandler(async (req, res) => {
const user = User.findById(req.user._id);
if (user) {
const { address, city, postalCode, country, email } = req.body;
const existAddress = await ShippingAddress.findOne({ userEmail: email });
if (existAddress) {
res.status(400);
throw new Error(
"User already has an address. If you want to change address, try CHANGE ADDRESS."
);
} else {
const createdAddress = await ShippingAddress.create({
user: req.user._id,
address,
city,
postalCode,
country,
userEmail: email,
});
if (createdAddress) {
res.status(201);
res.json({
address: createdAddress.address,
city: createdAddress.city,
postalCode: createdAddress.postalCode,
county: createdAddress.country,
email: createdAddress.userEmail,
});
} else {
res.status(400);
throw new Error("Address did not save");
}
}
} else {
res.status(404);
throw new Error("User not found");
}
});
// #desc change address
// #route PUT /api/shippingaddress
// #access Private
const changeAddress = asyncHandler(async (req, res) => {
const user = await User.findById(req.user._id);
if (user) {
const { email } = req.body;
const shippingAddress = await ShippingAddress.findOne({
userEmail: email,
});
if (shippingAddress) {
shippingAddress.address = req.body.address || shippingAddress.address;
shippingAddress.city = req.body.city || shippingAddress.city;
shippingAddress.postalCode =
req.body.postalCode || shippingAddress.postalCode;
shippingAddress.country = req.body.country || shippingAddress.country;
const updatedShippingAddress = await shippingAddress.save();
res.status(200);
res.json({
address: updatedShippingAddress.address,
city: updatedShippingAddress.city,
postalCode: updatedShippingAddress.postalCode,
county: updatedShippingAddress.country,
email: updatedShippingAddress.userEmail,
});
} else {
res.status(404);
throw new Error("Address not found");
}
} else {
res.status(404);
throw new Error("User not found");
}
});
export { getAddress, saveAddress, changeAddress };
authMiddleware file;
import jwt from "jsonwebtoken";
import User from "../models/userModel.js";
import asyncHandler from "express-async-handler";
const protect = asyncHandler(async (req, res, next) => {
let token = req.headers.token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
try {
// get token from req
token = req.headers.authorization.split(" ")[1];
// verify token
const decode = jwt.verify(token, process.env.JWT_SECRET);
// get user from token
req.user = await User.findById(decode.id).select("-password");
next();
} catch (error) {
res.status(401);
throw new Error("Not1 Authorized");
}
}
if (!token) {
res.status(401);
throw new Error("Not2 Authorized");
}
});
export default protect;
FOR FRONT-END;
shippingAction file;
import { createAsyncThunk } from "#reduxjs/toolkit";
import shippingServices from "./shippingServices";
// get address
export const getAddress = createAsyncThunk(
"shipping/get",
async (userInfo, thunkAPI) => {
try {
return await shippingServices.get(userInfo);
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
return thunkAPI.rejectWithValue(message);
}
}
);
// save address
export const saveAddress = createAsyncThunk(
"shipping/save",
async (addressInfo, thunkAPI) => {
try {
return await shippingServices.save(addressInfo);
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
return thunkAPI.rejectWithValue(message);
}
}
);
// update address
export const updateAddress = createAsyncThunk(
"shipping/update",
async (addressInfo, thunkAPI) => {
try {
return await shippingServices.update(addressInfo);
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
return thunkAPI.rejectWithValue(message);
}
}
);
shippingServices file;
import axios from "axios";
const SHIPPING_ADDRESS_URL = "/api/shippingaddress";
// save address
const save = async (addressInfo) => {
const config = {
headers: {
Authorization: `Bearer ${addressInfo.token}`,
},
};
const { data } = await axios.post(SHIPPING_ADDRESS_URL, addressInfo, config);
return data;
};
// get address
const get = async (userInfo) => {
const config = {
headers: {
Authorization: `Bearer ${userInfo.token}`,
},
};
const { data } = await axios.get(SHIPPING_ADDRESS_URL, userInfo, config);
return data;
};
// update address
const update = async (addressInfo) => {
const config = {
headers: {
Authorization: `Bearer ${addressInfo.token}`,
},
};
const { data } = await axios.put(SHIPPING_ADDRESS_URL, addressInfo, config);
return data;
};
const shippingServices = {
save,
get,
update,
};
export default shippingServices;
shippigPage file;
import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { Form, Button } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import FormContainer from "../components/FormContainer";
import Message from "../components/Message";
import Loader from "../components/Loader";
import { shippingSliceAction } from "../features/shipping/shippingSlice";
import { saveAddress, getAddress } from "../features/shipping/shippingAction";
function ShippingPage() {
const { user } = useSelector((state) => state.auth);
const { shippingAddress, isLoading, isSuccess, isError, message } =
useSelector((state) => state.shipping);
const [address, setAddress] = useState("");
const [city, setCity] = useState("");
const [postalCode, setPostalCode] = useState("");
const [country, setCountry] = useState("");
const [comMessage, setComMessage] = useState(null);
const dispatch = useDispatch();
const navigate = useNavigate();
useEffect(() => {
if (shippingAddress) {
setAddress(shippingAddress.address);
setCity(shippingAddress.city);
setPostalCode(shippingAddress.postalCode);
setCountry(shippingAddress.country);
} else {
const userInfo = {
token: user.token,
email: user.email,
};
dispatch(getAddress(userInfo));
}
}, []);
const submitHandler = (e) => {
e.preventDefault();
if (!user) {
navigate("/login");
} else {
if (!address || !city || !postalCode || !country) {
setComMessage("Please fill all fields");
setTimeout(() => setComMessage(null), 3000);
} else {
dispatch(
shippingSliceAction.takeAddress({
email: user.email,
address,
city,
postalCode,
country,
})
);
localStorage.setItem(
"userAddress",
JSON.stringify({
email: user.email,
address,
city,
postalCode,
country,
})
);
}
}
};
const saveContinue = () => {
if (!user) {
navigate("/login");
} else {
dispatch(
saveAddress({
email: user.email,
address,
city,
postalCode,
country,
token: user.token,
})
);
if (isSuccess) {
setComMessage("Your Address Saved");
setTimeout(() => dispatch(shippingSliceAction.reset()), 3000);
setTimeout(() => setComMessage(null), 3000);
setTimeout(() => navigate("/payment"), 4000);
}
}
};
return (
<FormContainer>
<h1>Shipping</h1>
{comMessage && <Message variant="danger">{comMessage}</Message>}
<Form onSubmit={submitHandler}>
<Form.Group controlId="address">
<Form.Label>Address</Form.Label>
<Form.Control
type="text"
placeholder="Enter Address"
value={address}
onChange={(e) => setAddress(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="city">
<Form.Label>City</Form.Label>
<Form.Control
type="text"
placeholder="Enter City"
value={city}
onChange={(e) => setCity(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="postalCode">
<Form.Label>Postal Code</Form.Label>
<Form.Control
type="number"
placeholder="Enter Postal Code"
value={postalCode}
onChange={(e) => setPostalCode(e.target.value)}
></Form.Control>
</Form.Group>
<Form.Group controlId="country">
<Form.Label>Country</Form.Label>
<Form.Control
type="text"
placeholder="Enter Country"
value={country}
onChange={(e) => setCountry(e.target.value)}
></Form.Control>
</Form.Group>
<Button className="shippingButton" type="submit" variant="primary">
Continue without saving
</Button>
{isLoading && <Loader />}
{isSuccess && <Message variant="success"></Message>}
{isError && <Message variant="danger">{message}</Message>}
<Button
className="shippingButton save"
type="button"
variant="secondary"
onClick={saveContinue}
>
Save my address and continue
</Button>
</Form>
</FormContainer>
);
}
export default ShippingPage;
// shippingServices.js
const { data } = await axios.get(SHIPPING_ADDRESS_URL, userInfo, config);
this should be
const { data } = await axios.get(SHIPPING_ADDRESS_URL, config);
Also stop using unnecessary packages like express-async-handler,
just cover entire middle-ware function body with try/catch block, call next(error) in catch block & it will work just fine.
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'm trying to check a login form with passport js and I want that when the status is correct, to log the user in but when it is incorrect to return him to the login page. I've tried doing this with an if else statement but it is not working as I've tried to console log the status and it shows nothing.
This is my frontend:
import React, {useState} from 'react'
import './login.css'
import axios from 'axios'
import { useHistory } from "react-router-dom";
function Login() {
const [username, setUsername] = useState("")
const [password, setPassword] = useState("")
const [data, setData] = useState(null)
const history = useHistory()
const onChangeUsername = (e) => {
setUsername(e.target.value)
}
const onChangePassword = (e) => {
setPassword(e.target.value)
}
const onSubmit = (e) => {
e.preventDefault()
const users = {
username: username,
password: password
}
axios.post('http://localhost:4000/users/login', users)
.then(res => console.log(res.data))
}
const loginUser = () => {
axios.get("http://localhost:4000/users/login", {
withCredentials: true
}).then(res => {
if(res.status === 200) {
setData(res)
return history.push("/home")
}
else if(res.status === 400) {
return history.push("/login")
}
console.log(res.status)
})
}
return (
<div>
<img src="https://www.freepnglogos.com/uploads/twitter-logo-png/twitter-logo-vector-png-clipart-1.png" className="twitterlogo____image"/>
<h1 className="login_____headertext">Log in to Twitter</h1>
<div className="placeholder_____global">
<form onSubmit={onSubmit}>
<input className="placeholder____div" placeholder="Phone, email or username" onChange={onChangeUsername}/>
<div>
<input className="placeholder____div" placeholder="Password" type="password" onChange={onChangePassword}/>
</div>
<div>
<button className="twitter___loginbuttonpage" onClick={loginUser}>Log in</button>
</div>
</form>
<div className="forgetPassword_____div">
<p>Forgot password?</p>
<p>ยท</p>
<p>Sign up for Twitter</p>
</div>
</div>
</div>
)
}
export default Login
Server side code:
const express = require('express');
const router = express.Router();
const Users = require('../models/users.model.js')
const passport = require("passport")
require('../authentication/passportConfig.js')(passport)
router.route('/').get((req, res) => {
Users.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error:' + err))
})
router.route('/login').post((req, res, next) => {
passport.authenticate("local" , (err, user, info) => {
if (err) throw err;
if (!user) res.status(400).send("No user exists");
else {
req.logIn(user, err => {
if (err) throw error;
res.status(200).send("Succesfully Authenticated")
})
}
})(req, res, next)
})
router.route('/login').get((req, res) => {
res.send(req.user)
})
router.route('/add').post(async(req,res) => {
const hashedPassword = await bcrypt.hash(req.body.password, 10)
const username = req.body.username
const password = hashedPassword
const email = req.body.email
const phone = req.body.phone
const monthOfBirth = req.body.monthOfBirth
const dayOfBirth = req.body.dayOfBirth
const yearOfBirth = req.body.yearOfBirth
const newUsers = new Users({
username,
password,
email,
phone,
monthOfBirth,
dayOfBirth,
yearOfBirth
})
newUsers.save()
.then (() => res.json("User Added"))
.catch(err => res.status(400).json('error' + err))
})
module.exports = router
Before reaching console you are returning the control in if else conditions.
move your console.log before if else.
const loginUser = () => {
axios.get("http://localhost:4000/users/login", {
withCredentials: true
}).then(res => {
console.log(res.status)
if(res.status === 200) {
setData(res)
return history.push("/home")
}
else if(res.status === 400) {
return history.push("/login")
}
})
}
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