my Signup.js file from where the request is initiating,
import React,{ useState } from 'react';
import isEmail from 'validator/lib/isEmail';
import isEmpty from 'validator/lib/isEmpty';
import equals from 'validator/lib/equals';
import { Link } from 'react-router-dom';
import { showErrMsg,showSuccessMsg } from '../Helpers/messages.js';
import { showLoading } from '../Helpers/loading';
import { signup } from '../../api/auth';
import './SignUp.css';
const SignUp = () => {
// filled this for testing purpose
const[formData,setFormData] = useState({
username: 'shivshankar',
email:'shivshankarkumar.pusa@gmail.com',
password:'1234',
password2:'1234',
successMsg:false,
errorMsg:false,
loading:false,
});
const {
username,
email,
password,
password2,
successMsg,
errorMsg,
loading,
} = formData;
const handleSubmit = (e) => {
e.preventDefault();
if(isEmpty(username) || isEmpty(email) || isEmpty(password) || isEmpty(password2)){
setFormData({
...formData,errorMsg : "All fields are Required"
})
}else if(!isEmail(email)){
setFormData({
...formData , errorMsg : "Invalid Email"
})
}else if(!equals(password,password2)){
setFormData({
...formData , errorMsg: "Passwords do not Match"
})
}else{
const { username , email , password} = formData;
const data = { username , email , password};
setFormData({
...formData,
loading : true,
})
signup(data)
.then(response => {
console.log("Axios signup success",response);
setFormData({
username:"",
email:"",
password:"",
password2:"",
loading:false,
successMsg:response.data.successMessage
})
})
.catch(err => {
console.log("Axios post error : " , err);
setFormData({...formData, loading : false});
});
}
}
my auth.jjs file from the axios post request is generating
import axios from 'axios';
export const signup = async (data) => {
const config = {
headers : {
'Content-Type' : 'applicaion/json',
},
};
console.log(data);
const response = await axios.post('/api/auth/signup', data, config);
return response;
};
now in server side server.js
const express = require('express');
const app = express();
const cors = require('cors');
const morgan = require('morgan');
const connectDB = require('./database/db');
const authRoutes = require('./routes/auth');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended : true }));
app.use(bodyParser.json());
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
app.use('/api/auth',authRoutes);
// app.post('/api/auth/signup',(req,res) => {
// console.log("inside signup");
// // res.send("api/auth/signup");
// });
connectDB();
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`listening to port ${port}`));
auth.js file for authRoutes`
const express = require('express');
const router = express.Router();
const { signupValidator, validatorResult } = require('../middleware/validator');
router.post('/signup', signupValidator, validatorResult);
module.exports = router;
my validator.js file
const { check, validationResult } = require('express-validator');
exports.signupValidator = [
check('username').not().isEmpty().trim().withMessage('All fields are required'),
check('email').isEmail().normalizeEmail().withMessage('Invalid Email'),
check('password').isLength({ min : 6 }).withMessage('Password must be 6 character long'),
];
exports.validatorResult = (req, res, next) => {
// console.log("request body" ,req.body);
const result = validationResult(req);
const hasErrors = !result.isEmpty();
// console.log(result);
if(hasErrors){
const firstError = result.array()[0].msg;
console.log("has errors",hasErrors);
console.log("result",result);
return res.status(400).json({
message : firstError,
});
}
next();
};
the data is being sent from front-end axios, but the data is not reaching to the back-end node server,
when i console.log(req.body)
or console.log(data)
it says undefined.
i am stuck here, can anyone please help me?? get this output in the console.
[0] result Result {
[0] formatter: [Function: formatter],
[0] errors:
[0] [ { value: undefined,
[0] msg: 'All fields are required',
[0] param: 'username',
[0] location: 'body' },
[0] { value: undefined,
[0] msg: 'Invalid Email',
[0] param: 'email',
[0] location: 'body' },
[0] { value: undefined,
[0] msg: 'Password must be 6 character long',
[0] param: 'password',
[0] location: 'body' } ] }
[0] POST /api/auth/signup 400 34.535 ms - 37
You have a typo in your auth.js file, you have set the Content-Type headers incorrectly it should be application/json
& not applicaion/json
import axios from 'axios';
export const signup = async (data) => {
const config = {
headers : {
'Content-Type' : 'application/json', //this should be application/json
},
};
console.log(data);
const response = await axios.post('/api/auth/signup', data, config);
return response;
};