I am beginner use React Js and Node Js, I get a problem, I cannot post my data from React Js to Node Js, I have been looking for the way but failed all, I don't know why.
This is my complete code.
This is my react file 'Register.js', run 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}')); //npm install -g node
and this is my node file 'users.js', run 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('/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 an user but getting an error:
xhr.js:178 POST http://localhost:3000/api/users/register 404 (Not Found) dispatchXhrRequest @ xhr.js:178 xhrAdapter @ xhr.js:12 dispatchRequest @ dispatchRequest.js:59 Promise.then (async) request @ Axios.js:51 Axios.(anonymous function) @ Axios.js:71 wrap @ bind.js:9 onSubmit @ Register.js:33 callCallback @ react-dom.development.js:100 invokeGuardedCallbackDev @ react-dom.development.js:138 invokeGuardedCallback @ react-dom.development.js:187 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:201 executeDispatch @ react-dom.development.js:461 executeDispatchesInOrder @ react-dom.development.js:483 executeDispatchesAndRelease @ react-dom.development.js:581 executeDispatchesAndReleaseTopLevel @ react-dom.development.js:592 forEachAccumulated @ react-dom.development.js:562 runEventsInBatch @ react-dom.development.js:723 runExtractedEventsInBatch @ react-dom.development.js:732 handleTopLevel @ react-dom.development.js:4477 batchedUpdates$1 @ react-dom.development.js:16660 batchedUpdates @ react-dom.development.js:2131 dispatchEvent @ react-dom.development.js:4556 interactiveUpdates$1 @ react-dom.development.js:16715 interactiveUpdates @ react-dom.development.js:2150 dispatchInteractiveEvent @ react-dom.development.js:4533 Register.js:35 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Error</title> </head> <body> <pre>Cannot POST /api/users/register</pre> </body> </html>
In the network also I am getting the same error:
Cannot POST /api/users/register
Hi @smit sanghvi, this forum is for APIs & Apigee API Management related queries. We also help with Nodejs questions, but you can try StackOverflow for questions related to ReactJS
User | Count |
---|---|
2 | |
2 | |
1 | |
1 | |
1 |