请求正文在服务器节点中显示未定义.js在 react.js 中附加表单请求时



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

所以在前端,我使用 axios 将信息发送到服务器

所以实际上我想做的是发送带有用户名,电子邮件,密码和图像的表单数据,但是每当我使用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);

用户控制器(我将它们注释掉以测试我得到的值(

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

您可以尝试这样做来发送表单数据:

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

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

我正在使用身体解析器,但后来我只是切换到强大的,谢谢!!

如果你是goinf来处理json格式作为请求,你可以使用npm bodyparser。

app.use(bodyParser.urlencoded({ extended: true, limit: '50MB' }((; app.use(bodyParser.json({ limit: '50MB', extended: true }((;

您可以在服务器.js文件中的路由声明之前使用上述行

最新更新