1

Tengo un API en Node, a la cual me quiero comunicar desde el front usando React. La cuestión es, que al iniciar sesión desde el front (con las credenciales correctas, probadas en Postman) obtengo la siguiente respuesta (en vez del token):

Response {type: "cors", url: "http://localhost:3001/api/auth/login", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3001/api/auth/login"

**Código del API:

index.js:

const express = require('express');
const app = express();
const cors = require('cors');

//Config
app.set('port', 3001)

//Middlewares
app.use(express.json());
app.use(cors());

//Routes
app.use(require('./routes/users'));
app.use(require('./routes/auth'));
app.use(require('./routes/tickets'));

//Server
app.listen(app.get('port'), () =>{
    console.log('Server listen on port', app.get('port'));
})

¿Que estoy haciendo mal?

2
  • cual seria la respuesta correcta? el 7 jun. 2020 a las 5:16
  • el token, ya que estoy tratando de iniciar sesión, probé desde el postman y recibo el token perfectamente, sin embargo, al iniciar sesión desde el front no recibo el token, sino la respuesta que dejé arriba. el 7 jun. 2020 a las 13:27

1 respuesta 1

1

Ya encontré el problema, nunca estuvo en el API, estuvo en el FRONT.

Debido a que HTTP manda la petición fragmentada, al momento de recibirla tenía que esperar que la petición llegara completa, anexo el código

antes:

send(data){
    fetch('http://localhost:3001/api/auth/login', {
       method: 'post',
       headers: {'Content-Type':'application/json'},
       body: JSON.stringify(
        {
            "mail": data.mail,
            "pass": data.pass
        }) 
    })
    .then(response =>{
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response.json()
    })
}

después:

send(data){
    fetch('http://localhost:3001/api/auth/login', {
       method: 'post',
       headers: {'Content-Type':'application/json'},
       body: JSON.stringify(
        {
            "mail": data.mail,
            "pass": data.pass
        }) 
    })
    .then(response =>{
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response.json()
    }).then(json => console.log(json));
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.