Задать вопрос
Nikito4ka_ka
@Nikito4ka_ka

Как исправит ошибку 500 (Internal Server Error) при отправке данных на сервер?

Всем привет! Делаю POST на сервер, но он выдает ошибку 500 (Internal Server Error).

Стек(React + node.js + express + mysql )
Для связи клиента и сервера использую PROXY

URL Api правильны так как сервер выдает что неправильный метод когда просто в браузере перехожу по ссылке
Ссылка: localhost:6660/api/auth/register
Ошибка: Cannot GET /api/auth/register

Сама ошибка
POST localhost:3000/api/auth/register 500 (Internal Server Error)
Для смены порта как уже говорил использую Proxy

Помогите пожалуйста разобраться в чем проблема.

Обновлено!
Вылетает из блока TRY в файле http.hooks.js (файл находится в React)
Код где вылетает

try {
      const response = await fetch(url, {
        method,
        body,
        headers
      });



Node.js

app.js

require('dotenv').config();
const express = require('express');
const sequelize = require('./db');

const PORT = process.env.PORT || 6660;

const app = express();

app.use(express.json({ extended: true }));

app.use('/api/auth', require('./routes/auth.routes'));

async function start() {
	try {
		await sequelize.authenticate();
		await sequelize.sync();
		app.listen(PORT, () => console.log(`Hello on port: ${PORT}`));
	} catch (e) {
		console.log('Server error: ' + e.message);
	}
}

start();


auth.routes,js

require('dotenv').config();
const { Router } = require('express');
const bcrypt = require('bcryptjs');
const { check, validationResult } = require('express-validator');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const router = Router();

//  /api/auth/register
router.post(
	'/register',
	[
		check('email', 'Invalid email').isEmail(),
		check('password', 'Minimum password length 8 characters').isLength({
			min: 8,
		}),
	],
	async (req, res) => {
		try {
			const errors = validationResult(req);

			if (!errors.isEmpty) {
				return res.status(400).json({
					errors: errors.array(),
					message: 'Incorrect registration data',
				});
			}

			const { email, password } = req.body;

			const cadidate = await User.findOne({ email });

			if (cadidate) {
				return res.status(400).json({ message: 'This user already exists' });
			}

			const hashedPassword = await bcrypt.hash(password, 12);
			const user = User(email, hashedPassword);

			await user.save();
			res.status(201).json({ message: 'User successfully created' });
		} catch (e) {
			res
				.status(500)
				.json({ message: 'Something went wrong, please try again' });
		}
	}
);

//  /api/auth/login
router.post(
	'/login',
	[
		check('email', 'Please enter a valid email').normalizeEmail().isEmail(),
		check('password', 'password must contain at least 8 characters').isLength({
			min: 8,
		}),
	],
	async (req, res) => {
		try {
			const errors = validationResult(req);

			if (!errors.isEmpty) {
				return res.status(400).json({
					errors: errors.array(),
					message: 'Incorrect login details',
				});
			}

			const { email, password } = req.body;

			const user = await User.findOne({ email });

			if (!user) {
				return res.status(400).jason({ message: 'User is not found' });
			}

			const isMatch = await bcrypt.compare(password, user.password);

			if (!isMatch) {
				return res.status(400).jason({ message: 'Invalid email or password' });
			}

			const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET_KEY, {
				expiresIn: '1h',
			});

			res.json({ token, userId: user.id });
		} catch (e) {
			res
				.status(500)
				.json({ message: 'Something went wrong, please try again' });
		}
	}
);

module.exports = router;


.env

# SERVER
PORT = 6660

# DATABASE
DB_HOST = 127.0.0.1
DB_PORT = 8889
DB_NAME = altairdb
DB_USER = root
DB_PASSWORD = root1



React js

AuthPage.js

import React from 'react';
import { useHttp } from '../../hooks/http.hook';
import './_auth.scss';

export const AuthPage = () => {
	const { loading, request } = useHttp();

	const [form, setForm] = React.useState({
		email: '',
		password: '',
	});

	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', data);
		} catch (e) {}
	};

	React.useEffect(() => {
		const signUpButton = document.getElementById('signUp');
		const signInButton = document.getElementById('signIn');
		const container = document.getElementById('container');

		signUpButton.addEventListener('click', () =>
			container.classList.add('right-panel-active')
		);

		signInButton.addEventListener('click', () =>
			container.classList.remove('right-panel-active')
		);
	});
	return (
		<div className='auth_page'>
			<div className='container' id='container'>
				<div className='form-container sign-up-container'>
					<div className='form'>
						<h1>Create Account</h1>
						<span>or use your email for registration</span>
						<input
							name='email'
							type='email'
							placeholder='Email'
							onChange={changeHandler}
						/>
						<input
							name='password'
							type='password'
							placeholder='Password'
							onChange={changeHandler}
						/>
						<button onClick={registerHandler} disabled={loading}>
							Sign Up
						</button>
					</div>
				</div>
				<div className='form-container sign-in-container'>
					<div className='form'>
						<h1>Sign in</h1>
						<span>or use your account</span>
						<input type='email' placeholder='Email' onChange={changeHandler} />
						<input
							type='password'
							placeholder='Password'
							onChange={changeHandler}
						/>
						<a href='/#'>Forgot your password?</a>
						<button>Sign In</button>
					</div>
				</div>
				<div className='overlay-container'>
					<div className='overlay'>
						<div className='overlay-panel overlay-left'>
							<h1>Welcome Back!</h1>
							<p>
								To keep connected with us please login with your personal info
							</p>
							<button className='ghost' id='signIn'>
								Sign In
							</button>
						</div>
						<div className='overlay-panel overlay-right'>
							<h1>Hello, Friend!</h1>
							<p>Enter your personal details and start journey with us</p>
							<button className='ghost' id='signUp'>
								Sign Up
							</button>
						</div>
					</div>
				</div>
			</div>
		</div>
	);
};



http.hook.js

import { useState, useCallback } from 'react';

export const useHttp = () => {
	const [loading, setLoading] = useState(false);
	const [error, setError] = useState(false);
	const request = useCallback(
		async (url, method = 'GET', body = null, headers = {}) => {
			setLoading(true);

			try {
				const response = await fetch(url, {
					method,
					body,
					headers,
				});

				const data = await response.json();

				console.log(data);

				if (!response.ok) {
					throw new Error(data.message || 'Something went wrong');
				}

				setLoading(false);

				return data;
			} catch (e) {
				setLoading(false);

				setError(e.message);
				throw e;
			}
		},
		[]
	);

	const clearError = () => setError(null);

	return { loading, request, error, clearError };
};


  • Вопрос задан
  • 423 просмотра
Подписаться 1 Простой 2 комментария
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы