Warm tip: This article is reproduced from stackoverflow.com, please click
forms node.js reactjs mern

Requestbody showing undefined in server node.js when attaching form request in react.js

发布于 2020-03-27 15:40:04

Having an issue where when I receive data in my server, it becomes undefined.

So on the frontend, I'm using axios to send information to the server

So actually what I want to do is to send a formdata with username, email, password and image but whenever i use formdata, the data appears to be undefined in the server

if I am not using formdata, it works like a charm

import './styles/Signup.css'
import './styles/AuthenticationPage.css'
import React, { useContext, useState } from 'react';
import Card from 'react-bootstrap/Card'
import Spinner from 'react-bootstrap/Spinner'
import Button from 'react-bootstrap/Button'
import { useForm } from 'react-hook-form'
import { useHistory } from "react-router-dom";
import axios from 'axios';
import Thumb from '../Components/Thumb';
import { Context } from '../hoc/Store'

const Signup = () => {

    let history = useHistory()
    const { register, handleSubmit, watch, errors } = useForm()
    const [image, setImage] = useState()
    const [ isSubmitting , updateIsSubmitting ] = useState(false)
    const [state, dispatch] = useContext(Context);

const onSubmit = async userData => {

    // hardcoded some dummy data to attach to axios, and it works, i get the value
    const body ={
        username: 'test'
    }
    //tried to put the data into a state first which then i attach to the value of formData.append, still doesnt work
    await dispatch({
        type: 'ADD_FORM',
        payload : userData
    })

    //tried to send a single dummy hardcoded data to the server but it just comes up as empty
    const formData =  new FormData();
    formData.append('username', 'test');
    // formData.set('email', state.formData.email);
    // formData.set('password', state.formData.password);
    //"/api/user/signup", formData, config

    try{
        axios.post("http://localhost:5000/api/user/signup", 
                formData, 
                {
                    headers: {
                        'Content-Type': 'multipart/form-data', 
                        }
                    }
                )
        .then( response => {
            console.log(response);
            // setTimeout(() => {history.push("/login")}, 2000)
            // console.log(response);
             });
    } catch (err) {
        alert(err.message)
                }
} 

const handleChange = (e) => {
    setImage(e.target.files[0])
  }

return  (
<Card className='AuthenticationPageBox'>

    <Card.Title>Sign up</Card.Title>
    <form onSubmit={handleSubmit(onSubmit)}>
        {/* <Card.Text>
            <label>Username</label>
            <input name="username" ref={register({ required: true, maxLength: 20 })} />
            {errors.username &&
            errors.username.type === "required" &&
            "Your input is required"}
            {errors.username &&
            errors.username.type === "maxLength" &&
            "Your input exceed maxLength"}
        </Card.Text>
        <Card.Text>
            <label>Email Address</label>
            <input name="email" ref={register({ required: true, pattern: /^(\D)+(\w)*((\.(\w)+)?)+@(\D)+(\w)*((\.(\D)+(\w)*)+)?(\.)[a-z]{2,}$/ })} />
            {errors.email &&
            errors.email.type === "required" &&
            "Your input is required"}
            {errors.email &&
            errors.email.type === "pattern" &&
            "Email address Invalid!"}
        </Card.Text>
        <Card.Text>
            <label>Password</label>
            <input type="password" name="password" ref={register({ required: true})} />
            {errors.password &&
            errors.password.type === "required" &&
            "Your input is required"}
        </Card.Text>
        <Card.Text>
            <label>Image</label>
            <input type ="file" name="file" ref={register({ required: true})} onChange={handleChange}/>
            {errors.file &&
            errors.file.type === "required" &&
            "Your input is required"}
        </Card.Text> */}
         <Thumb file={image}/>
        <input type="submit" />
    </form>
    <Button onClick={() => {history.push("/login")}}> </Button>
</Card>
    ) 
} 

export default Signup;

can someone help me out, my serverside code:

//route for logging in
router.post('/login', userControllers.login);

userControllers(i commented them out to test the value that I'm getting)

const signUp = async (req, res, next) => {

    //const { errors, isValid } = await validateRegisterInput(req.body);
    const header = req.header
    const { username } = req.body;
    console.log(req.file, req.body , username)

    res.status(201).json({ header : header, username })

    // Check validation
    // if (!isValid) {
    //     return res.status(400).json(errors.message);
    // }

    // const { username, email, password } = req.body;

    // const createdUser = new User ({
    //     username,
    //     email,
    //     password,
    //     image: "test",
    //     products:[],
    //     cart:[],
    //     orders:[]
    // });

    // const saltRounds = 12;

    // //Hash password before saving in database
    // bcrypt.genSalt(saltRounds, function(err, salt) {
    //   bcrypt.hash(createdUser.password, salt, (err, hash) => {
    //       try{
    //       createdUser.password = hash;
    //        createdUser
    //         .save()
    //     } catch (err) {
    //         const error = new HttpError ('Signup Failed, please try again later', 422);
    //         return next(error) 
    //         }
    //     });
    //   });

    // res.status(201).json({ user: createdUser})
};

headers set

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*')
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Authorization');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
    next();
})
Questioner
Kimimomo
Viewed
40
Coderman 2020-01-31 16:11

you can try this to send the form data :

axios({
    method: 'post',
    url: 'your_url',
    data : "username=test&email=test@mail.com"
}).then((response) => {
    // code ...
})

and at backend side in node js: use req.body.username and req.body.email to retrive data.