Получаю ответ от сервера 400 Bad Request
Разрабатываю фул-стек приложение на Mongo, React, Express, Node.js. Есть форма с полями "email" и "password" и кнопкой "Регистрация". При получение на сервере обо поля проходят валидацию на с помощью метода check (express-validator). При отправке формs ошибку 400. Застрял - все проверил, а ошибку найти не могу. Консоль node.js выдает следующую информацию.
Line 34:19: 'data' is assigned a value but never used no-unused-vars
[
[0] {
[0] value: undefined,
[0] msg: 'Not correct email',
[0] param: 'email',
[0] location: 'body'
[0] },
[0] {
[0] value: undefined,
[0] msg: 'Minimal password length is 6 symbols',
[0] param: 'password',
[0] location: 'body'
[0] }
[0] ]
Ниже код: Страница авторизации:
import React from "react";
import { useState } from "react";
import { useHttp } from "../hooks/http.hook";
import { useMessage } from "../hooks/message.hook";
import {useEffect} from 'react'
import { useContext } from "react";
import { AuthContext } from "../context/AuthContext";
export const AuthPage = ()=>{
const auth = useContext(AuthContext)
const message = useMessage()
const {loading, request, error, clearError }=useHttp()
const [form, setForm] = useState({
email: '', password: ''
})
useEffect(() => {
console.log('Error', error)
message(error)
clearError()
}, [error, message, clearError])
window.M.updateTextFields()
useEffect(()=>{
}, [])
const changeHandler = event =>{
setForm({...form, [event.target.name]: event.target.value})
}
const registerHandler = async () =>{
try{
const data = await request ('api/auth/register', 'POST', {...form})
console.log(data.message)
} catch(e){}
}
const loginHandler = async () =>{
try{
const data = await request ('api/auth/login', 'POST', {...form})
auth.login(data.token, data.userId)
} catch(e){}
}
return(
<div className="row">
<div className="col s6 offset-s3">
<h1>Сократи ссылку</h1>
<div className="card blue darken-1">
<div className="card-content white-text">
<span className="card-title">Авторизация</span>
<div>
<div className="input-field">
<input placeholder="Введите email"
id="email"
type="text"
name="email"
className="yellow-input"
onChange={changeHandler}
/>
<label htmlFor="email">Email</label>
</div>
<div className="input-field">
<input placeholder="Введите пароль"
id="password"
type="password"
name="password"
className="yellow-input"
onChange={changeHandler}
/>
<label htmlFor="password">Пароль</label>
</div>
</div>
</div>
<div className="card-action">
<button
className="btn yellow darken-4"
style={{marginRight: 10}}
disabled={loading}
onClick={loginHandler}
>
Войти
</button>
<button
className="btn grey lighten-1 black-text"
onClick={registerHandler}
disabled={loading}
>
Регистраиця
</button>
</div>
</div>
</div>
</div>
)
}
Роутер:
const { Router } = require('express')
const bcrypt = require('bcryptjs')
const config = require('config')
const jwt = require('jsonwebtoken')
const { check, validationResult } = require('express-validator')
const User = require('../models/User')
const router = Router()
// /api/auth/register
router.post(
'/register', [
check('email', 'Not correct email').isEmail(),
check('password', 'Minimal password length is 6 symbols')
.isLength({ min: 6 })
],
async(req, res) => {
try {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array(),
message: 'Not correct data during registration'
})
}
const { email, password } = req.body
const candidate = await User.findOne({ email })
if (candidate) {
return res.status(400).json({ message: 'Such User already exists' })
}
const hashedPassword = await bcrypt.hash(password, 12)
const user = new User({ email, password: hashedPassword })
await user.save()
res.status(201).jason({ message: 'User created' })
} catch (e) {
res.status(500).json({ message: 'Something goes wrong, try once more' })
}
})
module.exports = router
Хук http
import {useState, useCallback} from 'react'
export const useHttp = () => {
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const request = useCallback(async (url, method="GET", body=null, headers={}) =>{
setLoading(true)
try {
if(body){
body=JSON.stringify(body)
Headers['Content-Type']='application/json'
}
const response=await fetch(url, {method, body, headers})
const data = await response.json()
if (!response.ok){
throw new Error(data.message || "Something goes wrong")
}
setLoading(false)
return data
}catch(e){
console.log('Catch', e.message)
setLoading(false)
setError(e.message)
throw e
}
}, [])
const clearError = useCallback(() => setError(null),[])
return {loading, request, error, clearError}