Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React : POST and GET not found

I'm following this tutorial which I adapt to React Router v4.

I have these files :

auth.js

const express = require('express');
const validator = require('validator');

const router = new express.Router();

function validateLoginForm(payload) {
    const errors = {};
    let isFormValid = true;
    let message = '';

    if (!payload || typeof payload.email !== 'string' || payload.email.trim().length === 0) {
        isFormValid = false;
        errors.email = 'Please provide your email address.';
    }

    if (!payload || typeof payload.password !== 'string' || payload.password.trim().length === 0) {
        isFormValid = false;
        errors.password = 'Please provide your password.';
    }

    if (!isFormValid) {
        message = 'Check the form for errors.';
    }

    return {
        success: isFormValid,
        message,
        errors
    };
}

router.post('/login', (req, res) => {
    console.log("lol");
    const validationResult = validateLoginForm(req.body);
    if (!validationResult.success) {
        return res.status(400).json({
            success: false,
            message: validationResult.message,
            errors: validationResult.errors
        });
    }

    return res.status(200).end();
});


router.get('/login', (req, res) => {
    console.log(req.url);
});

router.get('/', (req, res) => {
    console.log(req.url);
    console.log("lmao")
});


module.exports = router;

index.js

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = new express.Router();
// tell the app to look for static files in these directories
app.use(express.static('./server/static/'));
app.use(express.static('./client/dist/'));
app.use(bodyParser.urlencoded({extended:false}));

const authRoutes = require('./server/routes/auth');

app.use('/login', authRoutes);

// start the server
app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000 or http://127.0.0.1:3000');
});

Base.jsx

import React from 'react';
import PropTypes from 'prop-types';
import { Link, NavLink } from 'react-router-dom';

const Base = ({ child }) => (
    <div>
        <div className="top-bar">
            <div className="top-bar-left">
                <NavLink to="/">React App</NavLink>
            </div>

            <div className="top-bar-right">
                <Link to="/login">Log in</Link>
            </div>

        </div>

        {child.render()}

    </div>
);

Base.propTypes = {
    child: PropTypes.object.isRequired
};
export default Base;

and app.jsx

import React from 'react';
import ReactDom from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import Base from './components/Base.jsx';
import HomePage from './components/HomePage.jsx';
import LoginPag from './components/LoginPag.jsx';

// for MaterialUI to work properly
injectTapEventPlugin();

const TestLogin = (props) => {
    return (<Base child={LoginPag}/>)
};

const TestBase = (props) => {
    return(<Base child={HomePage}/>)
};

ReactDom.render((<BrowserRouter><MuiThemeProvider muiTheme={getMuiTheme()}>
    <div>
    <Switch>
            <Route exact path="/" component={TestBase}/>
    </Switch>
    <Route exact path="/login" component={TestLogin}/>
    </div>
    </MuiThemeProvider>
</BrowserRouter>), document.getElementById('react-app'));

As you can see, I did a little "workaround" to have everything rendered nicely and it works. But it only works for Client-side routing.

I can't reload pages via f5 or refresh button, nor can I send form and get it through router.post(). It automatically results in a 404 not found.

I printed req.url in router.get('*') to see where the thing goes down and it appears that everywhere I go, the server still receives the address /. I believe the matter is with the <Link to> tag..

How can I fix this and get the server "follow" the client side routing ?

I'm using latest versions of Express, React, and React-Router. Thanks in advance

EDIT : Edited to take into account the remarks made by VivekN

like image 954
Gaëtan Boyals Avatar asked Jun 01 '26 07:06

Gaëtan Boyals


1 Answers

Change your index.js file to the below one:-

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = new express.Router();
// tell the app to look for static files in these directories
app.use(express.static('./server/static/'));
app.use(express.static('./client/dist/'));
app.use(bodyParser.urlencoded({extended:false}));

const authRoutes = require('./server/routes/auth');

app.use('/', authRoutes);

// start the server
app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000 or http://127.0.0.1:3000');
});

The problem with your code is that you had written when a request comes to your server which has /login in its path, then that should go inside auth.js file and inside that you should check for router.post('/') method. Either this or you change the index.js file to be

app.use('/', authRoutes);
like image 74
VivekN Avatar answered Jun 02 '26 21:06

VivekN



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!