温馨提示:本文翻译自stackoverflow.com,查看原文请点击:reactjs - Requestbody showing undefined in server node.js when attaching form request in react.js
forms node.js reactjs mern

reactjs - 当在react.js中附加表单请求时,请求正文在服务器node.js中显示未定义

发布于 2020-03-27 15:45:34

有一个问题,当我在服务器中接收数据时,数据变得不确定。

因此,在前端,我正在使用axios将信息发送到服务器

所以实际上我想做的是发送带有用户名,电子邮件,密码和图像的formdata,但是每当我使用formdata时,服务器中的数据似乎都是未定义的

如果我不使用formdata,它就像一个魅力

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;

有人可以帮我吗,我的服务器端代码:

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

userControllers(我将它们注释掉以测试我得到的值)

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})
};

标头集

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();
})

查看更多

查看更多

提问者
Kimimomo
被浏览
48
Coderman 2020-01-31 16:11

您可以尝试发送表单数据:

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

在节点js的后端:使用req.body.usernamereq.body.email检索数据。