问题描述
来自我的反应状态的数据之前通过 axios post 请求发送到我的服务器端点,并且我的数据库正在填充这些数据;但是,它不再起作用。 注意:当我在 handleSubmit 函数中控制台登录时,数据不会出现.. 我一直无法解决这个问题。当我通过 Postman 向同一端点发出请求时,它会很好地填充我的数据库。如果您注意到我没有看到的任何内容,请告诉我。
ModalForm.js(注册表单)
import React,{ useState } from 'react';
import axios from 'axios';
import '../styles/modal.css'
import {
browserRouter as Router,Link
} from 'react-router-dom';
const ModalForm = ({ show,formChange,setProfile }) => {
if (!show) {
return null;
}
let [user,setUser] = useState({
firstName: '',lastName: '',email: '',password: '',});
let handleChange = (e) => {
setUser({
...user,[e.target.name]: e.target.value
});
};
let handleSubmit = (e) => {
e.preventDefault();
let data = user;
setUser({[e.target.name]: e.target.value});
axios.post('/new/user',data)
.then(res => console.log(res))
.catch(err => console.error(err))
}
return (
<Router>
<div className='form-container'>
<h3>Sign Up</h3>
<form className='form-space' onSubmit={handleSubmit}>
<label className='form-text'>
First Name:
</label><br/>
<input type='text' name='firstName' onChange={handleChange}/><br/><br/>
<label className='form-text'>
Last Name:
</label><br/>
<input type='text' name='lastName' onChange={handleChange}/><br/><br/>
<label className='form-text'>
Email:
</label><br/>
<input type='email' name='email' onChange={handleChange}/><br/><br/>
<label className='form-text'>
Password:
</label><br/>
<input type='password' name='password' onChange={handleChange}/><br/><br/>
<Link to='/profile'>
<input type='submit' className='submitBtn' value='Sign Up' onClick={setProfile} />
</Link>
<Link to='/login' className='link'>
<p className='loginText' onClick={formChange}>Already a member?</p>
</Link>
</form>
</div>
</Router>
)
};
export default ModalForm;
服务器端点:
app.post('/new/user',(req,res) => {
let userData = req.body;
console.log('req body',userData);
bcrypt.hash(userData.password,saltRounds,(err,hash) => {
userData.password = hash;
if (err) console.log('Error hashing',err);
Users.create(userData,data) => {
console.log('created user:',data);
if (err) res.status(500).send(err);
else res.status(201).send(data);
});
});
});
注册架构
const mongoose = require('mongoose');
const { Schema } = mongoose;
const signupSchema = new Schema({
firstName: String,lastName: String,email: String,password: String,});
const Users = mongoose.model('Users',signupSchema);
module.exports = {
Users
};
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)