Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make http post request with reactJs and NodeJs

I have a registration form in one of my reactJs files, which takes all values of input fields (works as I expect).
SignUp.js

import React, { Component } from 'react';
import { Link } from 'react-router-dom';

class SignUpForm extends Component {
    constructor() {
        super();

        this.state = {
            email: '',
            password: '',
            username: '',
            hasAgreed: false,
            formErrors: {email: '', password: ''},
            emailValid: false,
            passwordValid: false,
            formValid: false
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(e) {
        let target = e.target;
        let value = target.type === 'checkbox' ? target.checked : target.value;
        let name = target.name;

        this.setState({[name]: value});
    }

    handleSubmit(e) {
        e.preventDefault();

        console.log('The form was submitted with the following data:');

        console.log([this.state.email, cryptr.encrypt(this.state.password), this.state.username, this.state.hasAgreed]);

       //I want to send my above data to node server

    }

    render() {
        return (
            <div className="FormCenter">
                <form onSubmit={this.handleSubmit} className="FormFields" method="POST" action="/register">
                    <div className="FormField">
                        <label htmlFor="name">Username</label>
                        <input type="text" id="name" placeholder="Enter your username" name="username" value={this.state.username} onChange={this.handleChange} />
                    </div>
                    <div className="FormField">
                        <label htmlFor="password">Password</label>
                        <input type="password" id="password" placeholder="Enter your password" name="password" value={this.state.password} onChange={this.handleChange} />
                    <div className="FormField">
                        <label htmlFor="email">E-Mail Address</label>
                        <input type="email" id="email" placeholder="Enter your email" name="email" value={this.state.email} onChange={this.handleChange} />
                    </div>
                    </div>

                    <div className="FormField">
                        <label>
                            <input type="checkbox" name="hasAgreed" value={this.state.hasAgreed} onChange={this.handleChange} /> I agree all statements in <a href="google.com">terms of service</a>
                        </label>
                    </div>
                </form>
            </div>
        );
    }
}

export default SignUpForm;

Now I want to send the mentioned data to the created node server.
server.js

const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "src/containers/user")));

//the request in which I expect input data
app.post('/register', (req, res) => {
    if (!req.body) return res.sendStatus(400);
    console.log(req.body, "body");
    res.send('welcome, ' + req.body.username)
});

app.listen(5000, () => {
    console.log("is listening on port 5000");
});

As I expect, in form tag writing method="POST" action="/register"would do it's job, but even the console.log from /register request is not responding.

Note: The next thing I should implement is to write all the data in txt file. So fetching the data in back end is a must.

like image 922
reactive Avatar asked Mar 03 '26 07:03

reactive


1 Answers

What you need to do is pass the data as an object to axios like so, which you indicated you have installed in your project.

const formData = {
    email: this.state.email,
    password: cryptr.encrypt(this.state.password)
    username: this.state.username,
    hasAgreed: this.state.hasAgreed
}

axios({
    method: 'post',
    url: '/register',
    data: formData,
    config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
    //handle success
})
.catch(function (response) {
    //handle error
});
like image 93
AnonymousSB Avatar answered Mar 04 '26 20:03

AnonymousSB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!