я пытаюсь вызвать какой-то регистр из реакции переднего на мой node.js обратно, используя ax ios, но я получил сообщение об ошибке 400:
POST http://localhost: 9000 / user / register 400 (неверный запрос), но я не вижу, в чем проблема с данными, которые я отправляю на сервер.
Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
Вот мой код:
import React, { useState } from 'react'
import Service from "../../services/Service";
import { Link } from 'react-router-dom';
const Register = () => {
const user = {
name: '',
email: '',
password: '',
confirmPassword: '',
}
const [userData, setUserData] = useState(user);
const [error, setError] = useState('');
const [submitted, setSubmitted] = useState(false);
const handleChange = e => {
setUserData({ ...userData, [e.target.id]: e.target.value })
}
const saveUser = e => {
e.preventDefault();
const data = {
name: user.name,
email: user.email,
password: user.password
};
Service.signUp(data)
.then(response => {
setUserData({
name: response.data.name,
email: response.data.email,
password: response.data.password
})
setSubmitted(true);
console.log(userData)
})
.catch(error => {
setError(error);
console.log(error);
})
}
const newUser = () => {
setUserData(user);
setSubmitted(false);
}
const { name, email, password, confirmPassword } = userData;
const btn = name === '' || email === '' || password === '' || password !== confirmPassword
? <button disabled>Inscription</button> : <button>Inscription</button>
// gestion erreurs
const errorMsg = error !== '' && <span>{error.message}</span>
return (
<div className="signUpLoginBox">
<div className="slContainer">
<div className="">
<div className="formContent">
<form onSubmit={saveUser}>
{errorMsg}
<h2>Inscription</h2>
<div className="inputBox">
<input type="text" id="name" onChange={handleChange} value={name} autoComplete="off" />
<label htmlFor="pseudo">Name</label>
</div>
<div className="inputBox">
<input type="email" id="email" onChange={handleChange} value={email} autoComplete="off" required />
<label htmlFor="email">Email</label>
</div>
<div className="inputBox">
<input type="password" id="password" onChange={handleChange} value={password} autoComplete="off" required />
<label htmlFor="password">Mot de passe</label>
</div>
<div className="inputBox">
<input type="password" id="confirmPassword" onChange={handleChange} value={confirmPassword} autoComplete="off" required />
<label htmlFor="confirmPassword">Confirmez le mot de passe</label>
</div>
{btn}
</form>
<div className="linkContainer">
<Link className="simpleLink" to="/login">Déjà inscrit? Connectez-vous </Link>
</div>
</div>
</div>
</div>
</div>
);
};
export default Register
мой файл аутентификации node.js:
const router = require('express').Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const { registerValidation, loginValidation } = require('./validation');
router.post('/register', async (req, res) => {
//LETS VALIDATE THE DATA BEFORE WE A USER
const {error} = registerValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);
//Checking if the user is already in the database
const emailExist = await User.findOne({email: req.body.email})
if(emailExist) return res.status(400).send('Email already exists');
//Hash passwords
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
//Create a new user
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashedPassword
});
try{
const savedUser = await user.save();
res.send( {user: user._id});
}catch(err){
res.status(400).send(err);
}
});
, а затем в моем приложении. js (узел) выглядит как:
const createError = require('http-errors');
const express = require('express');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const testAPIRouter = require('./routes/testAPI');
const disneyCharacterRouter = require('./routes/disneyCharacter');
const authRoute = require('./routes/auth');
const postRoute = require('./routes/posts');
const app = express();
dotenv.config();
//Connect to DB
mongoose.connect(process.env.DB_CONNECT, { useNewUrlParser: true }, () =>
console.log('connected to DB!')
);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Route Middleware
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/testAPI', testAPIRouter);
app.use('/disneyCharacter', disneyCharacterRouter);
app.use('/user', authRoute);
app.use('/posts', postRoute);
Проверка. js (узел):
const Joi = require('@hapi/joi');
//Register Validation
const registerValidation = (data) => {
const schema = Joi.object({
name: Joi.string()
.min(6)
.required(),
email: Joi.string()
.min(6)
.required()
.email(),
password: Joi.string()
.min(6)
.required()
});
return schema.validate(data);
};
http-common. js файл:
import axios from "axios"
export default axios.create({
baseURL: "http://localhost:9000",
headers: {
"Content-type": "application/json"
}
});
сервис. js:
import http from "../http-common";
const signUp = data => {
return http.post('/user/register', data);
};
Вы видите проблему?