M
M
maxemga2021-03-30 22:09:03
Express.js
maxemga, 2021-03-30 22:09:03

The request is not sent to the server, what should I do?

I'm trying to send a request to the server in order to upload them to the database, but the error keeps popping up

POST http://localhost:3000/api/auth/register 500 (Internal Server Error)

And I did everything I could, I tried, but it doesn't work
. Do you have any ideas? I'm new to Backe and I just don't know what to do, because I fixed the problem with Route with the help of a proxy and now everything is ok, but error 500

Here I have the main server script
app.use('/api/auth', require('./routers/authRouter'));

These are routers where the main manipulations are performed.
const {Router} = require('express');
const router = Router();
const User = require('../models/user');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const config = require('../config/default.json')

router.post('/register', async (req, res) => {
    try {

        const {email, name, password } = req.body;

        const candidate = await User.findOne({email});
    
        if (candidate) {
           return res.status(400).json({messenge: "Такой пользователь уже существует"})
        }
        const hashedPassword = await bcrypt.hash(password, 8);
        const user = new User({email, name, password: hashedPassword });
        await user.save()

        res.status(201).json({messenge: "Новый пользователь создан"})

    }
    catch (e) {
        res.status(500).json({ messenge: 'Что-то пошло не так' })
    }

})

Wrote Hook for Fetch
import { useCallback, useState } from "react"

export function useHttp() {
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null)

    const request = useCallback(async (url, method = 'GET', body = null, headers = {}) => {
        setLoading(true)
        try {         
            const req = await fetch(url, {
               method, body, headers
            })
            const data = await req.json()
            setLoading(false)
            if(!req.ok) {
                throw new Error(data.messege)
            }

        }
        catch(e) {
            setLoading(false);
            setError(e.messege);
            throw e
        }      
    }, [])
    const clearError = () => setError(null)

    return {error, loading, request, clearError}
}


And on the client, when I click on the button, I call this function
const Register = async(values) => {
        try {
            const data = await request('/api/auth/register', 'POST', values)
            console.log(data)  
        }
        catch(e) {
            console.log("Error" + e.name)
        }
    
    }


Made Proxy
"proxy": "http://localhost:5000/",

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question