简体   繁体   中英

express body-parser returns empty body in req object

I am a beginner to react and node and this will be a very basic problem. I am creating a basic react fronted with a node backend. I setup mysql database connection and all set. I want to insert user details using /createUser api call to store data to database. I run the server/app.js, react serve and index.js which contained my listener for /createUser. When I input username,password using my form, empty req.body object will be returned in express.post method while I am expecting the username and password I entered. In other case, when I start the listener, react front is not loading by giving the error below.

GET http://localhost:3000/%PUBLIC_URL%/manifest.json 404 (Not Found) manifest.json:1 Manifest: Line: 1, column: 1, Unexpected token.

It seems like node component cannot access my manifest file. Am I correct?

index.js

const express = require('express');
const bodyParser = require('body-parser');
const store = require('./store');
const app = express();
app.use(express.static('public'));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ type: 'application/*+json' }));

app.use(bodyParser.json());

app.post('/createUser', (req, res) => {
    console.log(req.body);
    store
        .createUser({
            username: req.body.username,
            password: req.body.password
        })
        .then(() => res.sendStatus(200))
})

app.listen(3001, () => {
    console.log('Server running on http://localhost:3001')
})

login.js

import React, { Component } from 'react';
import classes from './Login.css';

function post (path, data) {
    console.log(data);
    return window.fetch(path, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
}

function handleLoginClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');

    const Login = document.querySelector('.Login');
    const username = Login.querySelector('.username').value;
    const password = Login.querySelector('.password').value;
    post('/login', { username, password })
        .then(({ status }) => {
            if (status === 200) alert('login success')
            else alert('login failed')
        })
}

function handleSignupClick(e) {
    e.preventDefault();
    console.log('The link was clicked sign up.');

    const CreateUser = document.querySelector('.CreateUser')
    const username = CreateUser.querySelector('.username').value;
    const password = CreateUser.querySelector('.password').value;
    post('/createUser', { username, password })
}


class Login extends Component {

    componentDidMount() {
    }

    componentWillUnmount() {
    }

    render() {
        return (
            <div>
                <form className="Login">
                    <h1>Login</h1>
                    <input type="text" className="username" placeholder="username"/>
                    <input type="password" className="password" placeholder="password"/>
                    <input  type="submit" value="Login" onClick={handleLoginClick}/>
                </form>
                <form className="CreateUser">
                    <h1>Create account</h1>
                    <input type="text" className="username" placeholder="username"/>
                    <input type="password" className="password" placeholder="password"/>
                    <input type="submit" value="Create" onClick={handleSignupClick}/>
                </form>
            </div>
        );
    }

}
export default Login;

What's wrong with my code? Can someone please explain me.

my code : https://github.com/indunie/tms2

Try to replace bodyParser configuration to following lines of code:

app.use(bodyParser.json({ limit: '100mb' }));
app.use(bodyParser.urlencoded({ limit: '100mb', extended: false }));

This might help you

solved [ https://github.com/expressjs/express/issues/3881][1]

There are two solutions here:

  1. Change the URL to http://localhost:3001/manifest.json to match how you have express.static setup.
  2. Change express.static to app.use('/public', express.static('public')); such that http://localhost:3001/public/manifest.json will refer to the given file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM