Can not retrive user from mongodb using findOne - node.js

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: '',
});
};

Related

How to implement Cloudinary in node.js/React app?

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" });
}
}
};

how to go to a specific profile after login?

Hey I am trying to build a simple Login and Profile seeing app. Where you can Register and Login and after that it will take you to your Profile where whatever you wrote in the Registration will show. But i am stuck, I need this for my internship plase anyone help me?? Below I am posting API and front end code.
server.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const userRouter = require('./routes/user.route');
const loginRouter = require('./routes/login.route');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json());
app.use(cors());
const uri = process.env.ATLAS_URI;
mongoose
.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then((res) =>
console.log('MongoDb connected .....')
)
.catch((err) => console.log(err));
app.use('/users', userRouter);
app.use('/login', loginRouter);
app.listen(port, () => {
console.log(`App is running on port ${port}`);
});
user.route.js
const express = require('express');
const Router = express.Router();
const User = require('../models/user.model');
Router.route('/').get((req, res) => {
User.find()
.then((response) => res.json(response))
.catch((err) =>
res.status(400).json('Error: ' + err)
);
});
Router.route('/add').post((req, res) => {
const {
firstname,
lastname,
email,
contact,
password,
} = req.body;
const newUser = new User({
firstname,
lastname,
email,
contact,
password,
});
newUser
.save()
.then((response) => res.json(response))
.catch((err) =>
res.status(400).json('Error: ' + err)
);
});
Router.route('/:id').get((req, res) => {
User.findById(req.params.id)
.then((response) => res.json(response))
.catch((err) => res.json(err));
});
module.exports = Router;
login.route.js
const express = require('express');
const Router = express.Router();
const User = require('../models/user.model');
Router.route('/').post((req, res) => {
User.findOne({ email: req.body.email })
.then((user) => {
if (user) {
if (req.body.password === user.password) {
return res.json(user);
} else {
return res.json('wrong password');
}
} else {
return res.json('User not found');
}
})
.catch((err) => res.json('Error: ' + err));
});
module.exports = Router;
Front End
app.js
import React, { Component } from 'react';
import { BrowserRouter } from 'react-router-dom';
import { Route } from 'react-router';
import Login from './components/login';
import Signup from './components/signup';
import Profile from './components/profile';
export default class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Route
path='/'
exact
component={Login}
/>
<Route
path='/signup'
exact
component={Signup}
/>
<Route
path='/users/:id'
component={Profile}
/>
</div>
</BrowserRouter>
);
}
}
login.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
export default class Login extends Component {
constructor() {
super();
this.state = {
email: '',
password: '',
};
}
onChangeEmail = (event) => {
this.setState({
email: event.target.value,
});
};
onChangePassword = (event) => {
this.setState({
password: event.target.value,
});
};
handleSubmit = (event) => {
event.preventDefault();
const newLogin = {
email: this.state.email,
password: this.state.password,
};
axios
.post(
'http://localhost:5000/login',
newLogin
)
.then((res) => {
window.location =
'/users/' + res.data._id;
})
.catch((err) => console.log(err));
this.setState({
email: '',
password: '',
});
};
render() {
return (
<div
className='container'
style={{ width: '400px' }}>
<div style={{ marginTop: '200px' }}>
<form onSubmit={this.handleSubmit}>
<div className='mb-3'>
<label
htmlFor='Email'
className='form-label'>
Email address
</label>
<input
value={this.state.email}
onChange={this.onChangeEmail}
type='email'
className='form-control'
id='Email'
aria-describedby='emailHelp'
/>
<div
id='emailHelp'
className='form-text'>
We'll never share your email with
anyone else.
</div>
</div>
<div className='mb-3'>
<label
htmlFor='Password'
className='form-label'>
Password
</label>
<input
value={this.state.password}
onChange={this.onChangePassword}
type='password'
className='form-control'
id='Password'
/>
</div>
<div>
{`Dont have an account? Click `}
<Link to='/signup'>Here</Link>
</div>
<button
type='submit'
className='btn btn-primary'>
Submit
</button>
</form>
</div>
</div>
);
}
}
profile.js
import axios from 'axios';
import React, { Component } from 'react';
export default class Profile extends Component {
constructor() {
super();
this.state = {
Name: '',
LastName: '',
email: '',
};
}
componentDidMount() {
axios
.get('http://localhost:5000/users/')
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
}
render() {
return (
<div>
<h1>Name</h1>
<h3>LastName</h3>
<p>email</p>
</div>
);
}
}
res.redirect('/your_page')
Use this when the user is saved in the database or when user is successfully authenticated

How to Post Data Form to mongoDB with ReactJS using hooks

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

axios call in react returns index.html

I am attempting to make an axios call inside of a useEffect hook, but all that is returned is the html.index file. I understand that express will direct any calls to "/" to index.html but i have specific routes established and other safeguards in place, so i dont know why this is happening...
React Component:
import React, { Fragment, useState, useEffect } from "react";
//uuid for card element key
import { v4 as uuidv4 } from "uuid";
import API from "../utils/API";
//dummy data
import books from "../dummy.json";
//import components
import Card from "../components/Card";
import Searchbar from "../components/Searchbar";
const Bookshelf = () => {
useEffect(() => {
loadBooks()
});
const loadBooks = () => {
API.getAllBooks().then(res => console.log(res))
}
const [bookArray, setBookArray] = useState({
books,
});
return (
<Fragment>
<div className="bookshelf">
<Searchbar />
<div className="bookshelf__heading__container">
<h2 className="bookshelf__heading">
Release the Kraken of Knowledge!
</h2>
</div>
<div className="bookshelf__container">
<section className="bookshelf__gallery">
{bookArray.books.map((book) => (
<Card
key={uuidv4()}
title={book.title}
author={book.author}
image={book.image}
/>
))}
</section>
</div>
</div>
</Fragment>
);
};
export default Bookshelf;
My Express Server:
const express = require("express");
const PORT = process.env.PORT || 3306;
const app = express();
const { sequelize } = require("./models");
const authors = require("./routes/authors");
const books = require("./routes/books");
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"))
}
app.use("/api/authors", authors);
app.use("/api/books", books);
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "../client/build/index.html"));
});
sequelize.sync().then(() => {
app.listen(PORT, () => {
console.log(listening on ${PORT});
});
});
Axios call:
import axios from "axios";
export default {
getAllBooks: function(){
return axios.get("/api/books/all");
}
};
My routes:
const express = require("express");
const router = express.Router();
const { Op, json } = require("sequelize");
const { Author, Book } = require("../models");
//POST new book:
router.post("/add_book", (req, res) => {
Book.create(req.body)
.then((book) => {
res.status(200).json({ book });
})
.catch((err) => {
res.status(500).send(err);
});
});
//PUT edit book by id:
router.put("/edit/:id", (req, res) => {
Book.update(req.body, {
where: {
id: req.params.id,
},
})
.then((numChanged) => {
res.status(200).json({ changedRows: numChanged[0] });
})
.catch((err) => {
res.status(500).send(err);
});
});
//GET all books;
router.get("/all", (req, res) => {
Book.findAll({
include: [Author],
})
.then((books) => {
res.status(200).json(books);
return json(books)
})
.catch((err) => {
res.status(500).send(err);
});
});
//GET books by title:
router.get("/title/:title", (req, res) => {
Book.findOne({
where: {
title: req.params.title,
},
include: [Author],
})
.then((books) => {
res.status(200).json(books);
})
.catch((err) => {
res.status(500).send(err);
});
});
//GET books by title OR author:
router.get("/search/:search_term", (req, res) => {
Book.findAll({
include: [Author],
where: {
[Op.or]: [
{ title: { [Op.substring]: req.params.search_term } },
{ "$Author.firstName$": { [Op.substring]: req.params.search_term } },
{ "$Author.lastName$": { [Op.substring]: req.params.search_term } },
],
},
})
.then((result) => {
res.status(200).json(result);
})
.catch((err) => {
res.status(500).send(err);
});
});
//DELETE book by id:
router.delete("/book_id/:id", (req, res) => {
Book.destroy({
where: {
id: req.params.id,
},
})
.then((wasDeleted) => {
res.status(200).json({ deleted: wasDeleted !== 0 });
})
.catch((err) => {
res.status(500).send(err);
});
});
module.exports = router;
I also have a proxy server set up and as far as i can tell thats working, but perhaps it might be related somehow...
Please let me know what else i can provide to help figure this out, its driving me up the wall.
EDIT: So if i make the call and include http://localhost:8080/etc, it works. That tell me there is (probably) a problem with the proxy server not working or express not finding it whatever...

Pass data from react component to proxy(node server)

I set up a proxy to bypass CORS for the intended api in this react application. I'm having trouble to pass data from react component to proxy(nodeJS server). I've read a few links such as here and here but still have no clues.
/*React component*/
import React, { useState } from "react";
import axios from "axios";
export default function Mail() {
const [emailInput, setEmailInput] = useState('')
const getMail = () => {
axios.get("/list/members").then(json => {
console.log(json.data);
});
};
const subscribe = (email) => {
console.log('inside subscribe')
axios.post("/member", email)
.then(data => console.log('post succeeds'))
.catch(err => console.log(err))
}
const handleSubmit = e => {
e.preventDefault();
const email = {
email_address: `${emailInput}`,
status: "subscribed"
};
subscribe(email)
};
const handleChange = (e) => {
setEmailInput(e.target.value)
}
return (
<form onSubmit={handleSubmit}>
<input type="text" name="email" placeholder="enter your email" value={emailInput} onChange={handleChange}/>
<input type="submit" value="subscribe" />{" "}
</form>
);
}
In node server, I have
app.post("/member", (req, res) => {
const email = {
email_address: "axios1234#gmail.com",
status: "subscribed"
};
axios.post(
"https://<apilink>",
email,
{
withCredentials: true,
auth: {
username: "anystring",
password: "<apikey>"
}
}
).then(json => {
res.send(json.data)
}).catch(err => {
console.log(err);
})
});
I've checked that my conduit between react front end app and proxy server is working. I also examined both req and res in app.post("/member", (req, res) but found thatreq.body is undefined and couldn't find the email object that was passed in from react function component. Did I miss anything here?
Are you using a body-parser? If not, install body-parser and then change your code to this:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post("/member", (req, res) => {
const email = req.body.email_address;
axios.post(
"https://<apilink>",
email,
{
withCredentials: true,
auth: {
username: "anystring",
password: "<apikey>"
}
}
).then(json => {
res.send(json.data)
}).catch(err => {
console.log(err);
})
});

Resources