How to handle Node error response in React

Asked

Viewed 184 times

-1

Guys I started Act and recently I looked for various ways to treat the error but I do not understand why it does not work. I tested the Node in the isomnia and it’s all ok, in React I get the answer returning the data I need, but I can’t get the error message.

authController from Node.js

const User = require('../Models/users');
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const authConfig = require('../../Config/auth');
const crypto = require('crypto');
const mailer = require('../../Modules/mailer');

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

    const { email, password } = req.body;
    const user = await User.findOne({ email }).select('+password');

    if (!user) {
        return res.status(400).send({ error: 'E-mail nao encontrado ' });
    }

    if (!await bcrypt.compare(password, user.password)) {
        return res.status(400).send({ error: 'Senha invalida!' });
    }

    user.password = undefined;

    res.send({
        user,
        token: generateToken({ id: user.id }),
    });

});

module.exports = app => app.use('/auth', router);

(I only put part of the code)

Apiservice.js from React

const ApiService = {

    Login: users => {

        return fetch('http://localhost:8000/auth/authenticate', { method: 'POST', headers: { 'content-type': 'application/json' }, body: users })
            .then(res => ApiService.TrataErros(res))
            .then(res => res.json())
            .then(res => { return res });

    },


    TrataErros: res => {
        if (!res.ok) {
            throw Error(res.responseText);
        }

        return res;
    }

};

export default ApiService;

1 answer

0

Tried to give a console.log(res) in any return to the inves of res.responseText to see if any content is coming. In case something is coming look inside res data.. It usually comes inside him.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.