大家好,我的代码进度遇到了一些问题,我只是学习MERN遇到了问题,并尝试将前端连接到后端,但是我的代码遇到了一些问题,它发送了400个错误的请求,或者该值未正确发送到我的后端。我将redux用于状态处理程序。
Api / Users.js
router.post(
'/',
[
check('name', 'name is required')
.not()
.isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
'Please enter a password with 6 or more characters'
).isLength({ min: 6 })
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, password } = req.body;
try {
let user = await User.findOne({ email: email });
//see if user exists
if (user) {
return res
.status(400)
.json({ errors: [{ msg: 'User Already Exists' }] });
}
//Get Users Gravatar
const avatar = gravatar.url(email, {
s: '200',
r: 'pg',
d: 'mn'
});
user = new User({
name,
email,
avatar,
password
});
//encrypt the pasword
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
//return jsonwebtekon
const payload = {
user: {
id: user.id
}
};
jwt.sign(
payload,
config.get('jwtSecret'),
{ expiresIn: 360000 },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
这是我的注册组件(我只显示我将状态传递给后端的位置)
const Register = ({ setAlert, register }) => {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
password2: ''
});
const { name, email, password, password2 } = formData;
const onChange = e =>
setFormData({ ...formData, [e.target.name]: e.target.value });
const onSubmit = async e => {
e.preventDefault();
if (password !== password2) {
setAlert('password do not match', 'danger');
} else {
register({ name, email, password });
}
};
这是我的操作记录
import axios from 'axios';
import { setAlert } from './alert';
import { REGISTER_SUCCESS, REGISTER_FAIL } from './types';
export const register = ({ name, email, password }) => async dispatch => {
const config = {
header: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ name, email, password });
try {
const res = await axios.post('/api/users', body, config);
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
});
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
}
dispatch({
type: REGISTER_FAIL
});
}
};
在这种情况下,问题在于数据已发送到后端,但是它总是被称为错误并且发送了错误的请求(400),因为循环总是发送到此处
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
因为错误是使用键名,电子邮件,密码发送没有价值
我真的感到困惑,我应该在课程中观看更多视频,但仍然像这样