Reputation: 101
I am not able to post my data from React Js to Node Js, I have been looking for several resources but not able to solve it
This is my complete code.
This is my react file 'Register.js', running on port 3000 (http://localhost:3000/register)
import React, { Component } from 'react';
import axios from 'axios';
class Register extends Component {
//takes user input
constructor(){
super();
this.state={
name:'',
email:'',
password:'',
password2:'',
errors:{}
}
//joins it to onChange fun
this.onChange=this.onChange.bind(this);
this.onSubmit=this.onSubmit.bind(this);
}
onChange(e){
this.setState({[e.target.name]:e.target.value});
}
onSubmit(s){
s.preventDefault();
const newUser={
name:this.state.name,
email:this.state.email,
password:this.state.password,
password2:this.state.password2
}
axios.post('/api/users/register',newUser)
.then(res=> console.log(res.data))
.catch(err=>console.log(err.response.data));
}
render() {
return (
<div className="home">
<div className="dark-overlay landing-inner text-light">
<div className="container">
<div className="row">
<div className="col-md-12 text-center">
<h1 className="display-4 text-center">Sign Up</h1>
<p className="lead text-center">Create your Profile and start getting noticed by Employers!</p>
<div className="form-group">
<form onSubmit={this.onSubmit}>
<div className="form-group">
<input type="name" placeholder="Name" className="form-control" name="name" value={this.state.name} onChange={this.onChange}/>
</div>
<div className="form-group">
<input type="email" placeholder="Email" className="form-control" name="email" value={this.state.email} onChange={this.onChange}/>
</div>
<div className="form-group">
<input type="password" placeholder="Password" className="form-control" name="password" value={this.state.password} onChange={this.onChange} />
</div>
<div className="form-group">
<input type="password" placeholder=" Confirm Password" className="form-control" name="password2" value={this.state.password2} onChange={this.onChange}/>
</div>
<hr />
<input type="submit" className="btn btn-lg btn-success"/>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default Register;
This is the 'server.js' code:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const users=require('./routes/api/users');
const userprofile=require('./routes/api/userprofile');
const app=express();
//body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//db config
const db = require('./config/keys').mongoURI;
//connecting to database
mongoose
.connect(db)
.then(() => console.log('mongo is successfully Connected'))
.catch(err => console.log(err));
//passport middleware
app.use(passport.initialize());
//passsport config
require('./config/passport')(passport);
//testing the server
app.get('/',(req,res)=>res.send('working'));
//using routes for users and userprofile
app.use('/api/users',users);
app.use('/api/userprofile',userprofile);
//to connect to localhost
const port=process.env.PORT || 5000;
app.listen(port,()=> console.log('server running on ${port}'));
and this is my node file 'users.js', running on port 5000
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const keys = require('../../config/keys');
const passport = require('passport');
//bringing input validation
const validatingregister=require('../../validation/register');
const validatingrlogin=require('../../validation/login');
//loading User schema
const User=require('../../models/User');
router.get('/demo', (req, res) => res.json({ msg: 'user api Works' }));
//will check email address if exists or not
router.post('http://localhost:5000/api/users/register',(req,res)=>{
const { errors, isValid } = validatingregister(req.body);
// Checking Validation
if (!isValid) {
return res.status(400).json(errors);
}
User.findOne({email:req.body.email})
.then(user=>{
if(user){
return res.status(400).json({email:"email already registered"});
}
//if not then will create newuser
else{
const newUser=new User({
name:req.body.name,
email:req.body.email,
password:req.body.password
});
//bcrypt is for hashing the password of the user
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser
.save()
.then(user => res.json(user))
.catch(err => console.log(err));
});
}
)}
})
})
//login route
router.post('/login', (req, res) => {
const { errors, isValid } = validatingrlogin(req.body);
// Check Validation for login
if (!isValid) {
return res.status(400).json(errors);
}
const email = req.body.email;
const password = req.body.password;
//finding user by email
User.findOne({ email }).then(user => {
//if no user with this email
if(!user){
return res.status(400).json("No user with this email");
}
//checking pass
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
// User Matched
const payload = { id: user.id, name: user.name, avatar: user.avatar }; // Create JWT Payload
// Sign Token
jwt.sign(
payload,
keys.secretOrKey,
{ expiresIn: 3600 },
(err, token) => {
res.json({
success: true,
token: 'Bearer ' + token
});
}
);
}
else{
res.status(400).json({password:"incorrect password"});
}
})
});
})
router.get(
'/current',
passport.authenticate('jwt', { session: false }),
(req, res) => {
res.json({
id: req.user.id,
name: req.user.name,
email: req.user.email
});
})
module.exports = router;
I am trying to register a user but getting an error:
Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
(anonymous function)
src/components/auth/Register.js:36
33 |
34 | axios.post('http://localhost:5000/api/users/register',newUser)
35 | .then(res=> console.log(res.data))
> 36 | .catch(err=>console.log(err.response.data));
37 | }
38 | render() {
39 | return (
Upvotes: 0
Views: 4147
Reputation: 545
As you can see from the network request you included:
xhr.js:178 POST http://localhost:3000/api/users/register 404 (Not Found)
You are sending your request to localhost:3000
. As you mentioned you have your Node server running at port 5000
. Which means your requests should be send to there.
Now you have multiple options in the situation.
1) Enable Cross-Origin Resource Sharing. This will allow you to send request from one origin to another.
2) Let your Node server serve your frontend code so you don't have separate origins to deal with.
Personally I prefer option 1 because it helps me separate my concerns.
Since you're using express you'll need to add this to your server code:
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
For more info on enabling CORS for check Enable CORS
And your client code(React) should be updated to call the correct origin like so
onSubmit(s){
// your code ...
axios.post('//localhost:5000/api/users/register', newUser)
.then(res=> console.log(res.data))
.catch(err=>console.log(err.response.data));
}
}
Upvotes: 4