0

I am building a registration page for my project and encountered an error Cannot POST / on rendering the web page .Earlier i also have made a login page which is working correctly by using almost same syntax. Here are my files.

1)Registration.js

import React,{Component} from 'react';
import Axios from 'axios';

class Registration extends Component{
    constructor(props)
    {
        super(props);
    this.state={
        name:"",
        gender:"",
        city:"",
        state:"",
        email:"",
        password:""
    };
}
    render(){
        
        return(
            <div class="main">

        <h1>Sign up</h1>
        <div className="container">
            <div className="sign-up-content">
                <form method="POST" class="signup-form" onSubmit={this.onSubmit}>
                    <h2 className="form-title">Register yourself below:-</h2>
                    <div className="form-textbox">
                        <label for="name">Full name</label>
                        <input type="text" name="name" id="name" value={this.state.name} onChange={this.onChangeName}/>
                    </div>
                    
                    <div className="form-textbox">
                        <label for="Gender">Gender</label>
                        <input type="text" name="gender" id="gender" value={this.state.gender} onChange={this.onChangeGender}/>
                    </div>

                    <div className="form-textbox">
                        <label for="City">City</label>
                        <input type="text" name="city" id="city" value={this.state.city} onChange={this.onChangeCity}/>
                    </div>

                    <div className="form-textbox">
                        <label for="State">State</label>
                        <input type="text" name="State" id="State" value={this.state.state} onChange={this.onChangeSate}/>
                    </div>
                    
                    <div className="form-textbox">
                        <label for="email">Email</label>
                        <input type="email" name="email" id="email" value={this.state.email} onChange={this.onChangeEmail}/>
                    </div>

                    <div className="form-textbox">
                        <label for="pass">Password</label>
                        <input type="password" name="pass" id="pass" value={this.state.password} onChange={this.onChangePassword}/>
                    </div>

                    {/* <div className="form-group">
                        <input type="checkbox" name="agree-term" id="agree-term" class="agree-term" />
                        <label for="agree-term" class="label-agree-term"><span><span></span></span>I agree all statements in  <a href="#" class="term-service">Terms of service</a></label>
                    </div> */}

                    <div className="form-textbox">
                        <input type="submit" name="submit" id="submit" class="submit" value="Create account" />
                    </div>
                </form>

                <p className="loginhere">
                    Already have an account ?<a href="#" class="loginhere-link"> Log in</a>
                </p>
            </div>
        </div>

    </div>
        );
    };
    onChangeName=(e)=>{
        this.setState({
            name:e.target.value 
        });
    };
    onChangeGender=(e)=>{
        this.setState({
            gender:e.target.value
        });
    };
    onChangeCity=(e)=>{
        this.setState({
            city: e.target.value
        });
    };
    onChangeSate=(e)=>{
        this.setState({
            state:e.target.value
        });
    };
    onChangeEmail=(e)=>{
        this.setState({
            email:e.target.value
        });
    };
    onChangePassword=(e)=>{
        this.setState({
            password:e.target.value
        });
    };
    onSubmit=(e)=>{
        console.log("inside on submit");
        const vals={...this.state};
        Axios.post("http://localhost:4200/register",vals).then(res=>console.log(res.data));
    };
}

export default Registration;

2)App.js

import React from 'react';
import Login from './Login';
import Registration from './Registration';
const App=()=>(
<Registration />
);

export default App;

3)index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />,document.getElementById('root'));

4)Node js server (server.js)

const express=require('express');
const bodyParser=require('body-parser');
const mysql=require('mysql');
const cors=require('cors');


const app=express();

app.use(cors());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

const con=mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'root',
    database:'reactProject'
});

// app.post('/login',(request,resposne)=>{
//     const email=request.body.email; 
//     const password=request.body.password;
//     console.log(email+"   "+password)
//     const sql='select * from login where email = "'+email+'" and password="'+password+'" ';
//     con.query(sql,(err,result)=>{
//         if(result.length)
//         {
//             console.log(result);
//             console.log("signed in");
//         }
//         else{
//             console.log(result);
//             console.log("Not signed");
//         }
//     });
// });

app.post('/register',(request,resposne)=>{
    const name=request.body.name;
    const gender=request.body.gender;
    const city=request.body.city;
    const state=request.body.state;
    const email=request.body.email;
    const password=request.body.password;
    console.log(name+" "+gender);
    const sql=`insert into register(name,gender,city,state,email,password) values('${name}','${gender}','${city}','${state}','${email}','${password}')`;
    con.query(sql,(result,error)=>{
        console.log(result);
    });
});
app.listen(4200,()=>{
    console.log("Server at 4200");
});

The above files are server.js,App.js,index.js,Registration it might be that whenever i click on submit it doesnot go inside onSubmit function .

1 Answer 1

1

In React, when you create a custom function to handle form submission, you need to call event.preventDefault(). The problem you are getting is due to the fact that your HTML is trying to send a post request when you submit the form, which you haven't set it up to do.

Here is a similar question where you can find more detailed information: React - Preventing Form Submission.

So, a way to fix this would be to change your onSubmit function to something like this:

onSubmit=(e)=>{
    console.log("inside on submit");
    e.preventDefault();
    const vals={...this.state};
    Axios.post("http://localhost:4200/register",vals).then(res=>console.log(res.data));
};
Sign up to request clarification or add additional context in comments.

2 Comments

then why my login.js worked without event.preventDefault() ?
I wouldn't be able to tell you since the code for your login component isn't posted here. My first guess would be that that on that component your login button isn't in a form, or that you didn't give the button a submit value, but that's just a guess. Either way, did adding preventDefault fix your problem?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.