fellinlovewithaman
fellinlovewithaman

Reputation: 339

React form data isn't being sent to express backend

I've followed several tutorials and SO posts, but I'm having issues sending data from a React form to the backend. I've tried both fetch and axios and nothing seems to be working. I've checked the network tab and can see that the request has been sent to the correct URL and it has returned a 200 code - but nothing is being logged in the back end.

App.js

// Require modules
const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
var cors = require('cors');

const app = express();
app.use(cors());

// Set up
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const port = 5000;

// Mongoose
mongoose.connect("mongodb+srv://georgegilliland:[email protected]/DPFootball?retryWrites=true&w=majority", {useNewUrlParser: true}, ()=>{
    console.log("DB connected")
});

// Controllers
let login = require('./controllers/login');

app.use('/api/login', function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader('Access-Control-Allow-Methods', '*');
    res.setHeader("Access-Control-Allow-Headers", "*");
    res.end();
});

// POST /login
app.post("/api/login", function(req, res) {
    console.log(req.body)
});

app.listen(port, () => {
    console.log("Server is on, baby")
})

login.js

import React, { Component } from 'react';
import axios from 'axios';
import './login.css';

class Login extends Component{  

    constructor(props) {
        super(props)
        this.state = {
        email: "",
        password: ""
        }
    }

    onChange = (e) => {
        this.setState({ [e.target.name]: e.target.value });
    }

    handleSubmit = e => {
        e.preventDefault();

        const { email, password } = this.state;

        const user = {
        email,
        password
        };

        axios
        .post('http://localhost:5000/api/login', user)
        .then(() => console.log('done'))
        .catch(err => {
            console.error(err);
        });
    };

    render(){
        return (
            <div id="login">
                <div className="background-inner-container">
                    {/* <p>{this.state.response}</p> --> */}
                    <div className="login-register-container padding-top padding-bottom padding-left padding-right">
                        <div className="login-register-title">Account Login</div>
                        <form onSubmit={this.handleSubmit}>
                            <input className="form-input" type="email" id="email" name="email" placeholder="Enter Email" onChange={this.onChange}/>
                            <input className="form-input" type="password" id="password" name="password" placeholder="Enter Password" onChange={this.onChange}/>
                            <button className="form-button" type="submit">Login</button>
                        </form>
                    </div>
                </div>
            </div>
        );
    } 
}

export default Login

Upvotes: 0

Views: 504

Answers (1)

thetw
thetw

Reputation: 88

The problem is the Express middleware. An Express middleware takes three parameters: (req, res, next). Currently you are omitting the third parameter next, which is needed to forward the request to the following handlers. Also you are currently ending the response with res.end() before the POST handler function is reached.

Try this:

app.use('/api/login', function (req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader('Access-Control-Allow-Methods', '*');
    res.setHeader("Access-Control-Allow-Headers", "*");
    next();
});

I've removed the res.end() and called the next() function instead in order to proceed with the request.

EDIT By the way, if you only want to set CORS header, there's a handy and very common Express middleware called cors, which is highly customizable and will fit your needs. You can use it like this:

const cors = require('cors')
// ...

app.use(cors())

Upvotes: 1

Related Questions