This is my index.js backend side
//Body-Parser to JSON
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors({
origin: "http://localhost:3000",
credentials: true
}))
//Session
app.use(session({
secret: 'secretcode',
resave: true,
saveUninitialized: true
}))
app.use(cookieParser('secretcode'))
app.get('/' , (req , res) => {
res.send("HELLO WORLD")
console.log(process.env.MONGO_URL process.env.MONGO_MIDDLE process.env.MONGO_ENDPOINT)
})
//Route for sending the email
app.use(contactRoutes)
//Routes for authentication
app.use(authenticationRoutes)
The authentication Routes file
//Register User
router.post('/registerUser' , authentication.registerUser)
module.exports = router
The registerUser.js is like this
const Customer = require('../models/Customer.js')
const registerUser = (req , res) => {
//Checks to see if that email is already being used
Customer.findOne({Email: req.body.data.Email} , async (err , doc) => {
if (err) throw err;
if(doc) res.json("Already Exists");
//If user does not exist then create one
if(!doc) {
const newCustomer = new Customer({
Email: req.body.data.Email,
Full_Name: req.body.data.Full_Name,
Phone_Number: req.body.data.Phone_Number,
Password: req.body.data.Password
})
await newCustomer.save()
res.json({message: "Created"})
}
})
}
module.exports = {
registerUser
}
My axios request on the frontend is like this
const signupHandler = async () => {
await axios.post('http://localhost:4000/registerUser' , {
data: {
Email: email,
Full_Name: fullName,
Password: password,
Phone_Number: phoneNumber
},
withCredentials: true
}).then((res) => {
console.log(res.message)
})
}
Basically the console.log(res.message) part is not console logging anything. In the registerUser controller the code successfully saves the data to the database with no errors and moreover after operation I am not getting any error in the console. So i am just wondering why it is not showing on the frontend. Is there something I am missing?
CodePudding user response:
Axios returns data in the data property:
const signupHandler = async () => {
const { data } = await axios.post("http://localhost:4000/registerUser", {
data: {
Email: email,
Full_Name: fullName,
Password: password,
Phone_Number: phoneNumber,
},
withCredentials: true,
});
console.log(data.message);
};
CodePudding user response:
The page was refreshing on submit and that was what was causing the json message to not show up. I fixed it by simply preventing page from refreshing on submit.
const signupHandler = async (e) => {
e.preventDefault()
const { data } = await axios.post("http://localhost:4000/registerUser", {
data: {
Email: email,
Full_Name: fullName,
Password: password,
Phone_Number: phoneNumber,
},
withCredentials: true,
});
console.log(data.message);
};