在react.js中附加表单请求时,在server node.js中显示未定义的Requestbody
当我在我的服务器中接收数据时,会出现未定义的问题 因此,在前端,我使用axios将信息发送到服务器 因此,实际上我想做的是发送一个带有用户名、电子邮件、密码和图像的formdata,但每当我使用formdata时,服务器中的数据似乎未定义 如果我不使用formdata,它就像一个符咒在react.js中附加表单请求时,在server node.js中显示未定义的Requestbody,node.js,reactjs,forms,mern,Node.js,Reactjs,Forms,Mern,当我在我的服务器中接收数据时,会出现未定义的问题 因此,在前端,我使用axios将信息发送到服务器 因此,实际上我想做的是发送一个带有用户名、电子邮件、密码和图像的formdata,但每当我使用formdata时,服务器中的数据似乎未定义 如果我不使用formdata,它就像一个符咒 import './styles/Signup.css' import './styles/AuthenticationPage.css' import React, { useContext, useState
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;
userControllers(我将它们注释掉以测试我得到的值)
标题集
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.username
和req.body.email
来检索数据。我正在使用body解析器,但后来我切换到了强大,谢谢 如果要处理json格式作为请求,可以使用npm bodyparser
use(bodyParser.urlencoded({extended:true,limit:'50mb'}));
use(bodyParser.json({limit:'50mb',extended:true}))
您可以在server.js文件中的路由声明之前使用上一行您使用的是哪种主体解析器?一些正文解析器使用
req.fields
(例如,强大的)而不是req.body
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 ...
})