I am doing the project using MERN stack. So I have compiled the code successfully by running npm start on both client side and server side. It will open http://localhost:3000/ when I fill the data and click on submit. It is not sending the data to mongodb.
Want to know whether this problem occurs on client side or server side.
As in given picture it is showing error in stepContext.js
Here is code of stepContext.js which comes under client side
stepContext.js
import React, { createContext, useState } from 'react'
import { useHistory } from 'react-router-dom';
import axios from 'axios'
export const multiStepContext = createContext();
export default function StepContext(props) {
const history = useHistory();
const [currentStep , setCurrentStep] = useState(1);
const [userData , setUserData] = useState([]);
const [finalData , setFinalData] = useState([]);
const [transferData , setTransferData] = useState([]);
async function submitData(){
setFinalData(finalData => [...finalData,userData]);
console.log(userData)
await axios.post("/add",userData);
setUserData('');
setCurrentStep(1);
history.push("/customers");
}
async function sendMoney() {
await axios.post("/customer/money" , transferData);
history.push("/customers");
}
return (
<multiStepContext.Provider value={{currentStep, setCurrentStep,userData , setUserData,finalData , setFinalData, submitData,transferData,setTransferData,sendMoney}}>
{props.children}
</multiStepContext.Provider>
)
}
Backend code
index.js
const express = require('express')
const mongoose = require('mongoose')
const app = express();
app.use(express.json());
const PORT = 5000;
const DB = 'mongodb+srv://salunkherushikesh859:<passwd>@cluster0.tpdffqx.mongodb.net/login?retryWrites=true&w=majority'
mongoose.connect(DB,{
useNewUrlParser:true,
useCreateIndex:true,
useFindAndModify:false,
useUnifiedTopology:true
}).then(() => console.log("DB connected"))
.catch((e) => console.log(e))
app.use(express.json());
const userRoute = require("./routes/userData")
app.use(userRoute)
if ( process.env.NODE_ENV === "production"){
app.use(express.static("client/build"));
const path = require("path");
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
})
}
app.listen(PORT,() => console.log(`PORT is running at ${PORT}`))
I have defined routes in userdata.js file
Here is code
const express = require("express");
const transactions = require("../models/transactionSchema");
const router = express.Router();
const user = require("../models/userSchema");
router.post("/add", async (req, res) => {
const {
firstName,
lastName,
} = req.body;
if (
!firstName ||
!lastName ||
) {
return res.status(400).json({ msg: "Please fill all the details" });
}
const newUser = new user({
firstName,
lastName,
});
await newUser.save();
});
router.get("/customers", async (req, res) => {
try {
const User = await user.find();
res.send(User);
console.log(User)
// res.status(200).json(User.favourite);
// console.log(User.favourite)
} catch (e) {
console.log(e);
res.status(500).json();
}
});
router.get("/customers/:id", async (req, res) => {
// const { id} = req.body;
// console.log(req.params.id);
const data = await user.findById(req.params.id);
// console.log(data);
if (data) {
res.send(data);
console.log(data);
}
});
router.put("/customer/money", async (req, res) => {
// console.log(req.body)
try {
const { id, count, id2 } = req.body;
const data = await user.findById(id);
const data2 = await user.findById(id2);
data2.amount = count + data2.amount;
data.amount = data.amount - count;
data.save();
data2.save();
res.send("updated successfull");
} catch (e) {
console.log(e.message);
}
// data.update({amount:amount1})
// res.send("The amount is debited rupees from _ and creidet to rupess _ ")
});
router.post("/transactions" , async(req,res) => {
try {
const { id, count, id2 } = req.body;
const data = await user.findById(id);
const data2 = await user.findById(id2);
// console.log(req.body);
const newTrans = new transactions({
userOne : data.name,
userTwo:data2.name,
amount:count
})
await newTrans.save();
} catch (e) {
console.log(e);
}
})
router.get("/gettransactions", async (req,res) => {
try {
const data = await transactions.find();
res.send(data);
// console.log(data)
} catch (e) {
console.log(e);
res.status(500).json();
}
})
module.exports = router;
2
Answers
After referring many articles finally I got a solution . By referring @sachin answer I got
'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'
Then I followed certain steps:-
Stop the Node.js server.
Run below command
Add following lines to your server.js or index.js
then after restarting the server and client side it is working fine.
Your backend code is running on port 5000.
You have mentioned the API as
/add
in your react code which will hit to port 3000.Instead, try replacing
/add
withhttp://localhost:5000/add