API request error on localhost: "Possible Unhandled Promise Rejection"

Asked

Viewed 410 times

0

I am having a problem at the moment of requesting my local API with React Native. Request through Postman works correctly, by React Native error occurs:

Possible Unhandled Promise Rejection

My request code in React Native:

import AsyncStorage from '@react-native-community/async-storage';
const BASE_API = 'http://127.0.0.1:8082';

export default {
    checkToken: async (token) => {
        const req = await fetch(`${BASE_API}`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({token})
        });
        const json = await req.json();        
        return json;
    },
    signIn: async (academia, usuario, senha) => {

        console.log(`${BASE_API}/create`);

        const req = await fetch(`${BASE_API}/create`, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({academia, usuario, senha})
        });
        const json = await req.json();       
        return json;
    },
};

My API code in Node.js:

const restify = require('restify');
const errs = require('restify-errors');
const cors = require('cors');

const server = restify.createServer({
  name: 'myapp',
  version: '1.0.0'
});

var knex = require('knex')({
    client: 'mysql',
    connection: {
      host : '127.0.0.1',
      user : 'root',
      password : '',
      database : 'testeapi'
    }
  });

server.use(restify.plugins.acceptParser(server.acceptable));
server.use(restify.plugins.queryParser());
server.use(restify.plugins.bodyParser());

server.listen(8082, function () {
  console.log('%s listening at %s', server.name, server.url);
});

// rotas REST
server.use((req, res, next) => {
    //Qual site tem permissão de realizar a conexão, no exemplo abaixo está o "*" indicando que qualquer site pode fazer a conexão
    res.header("Access-Control-Allow-Origin", "*");
    //Quais são os métodos que a conexão pode realizar na API
    res.header("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE');
    server.use(cors());
    next();
});

server.get('/', (req, res, next) => {
    
    knex('rest').then((dados) => {
        res.send(dados);
    }, next)
    
});

server.post('/create', (req, res, next) => {
    
    knex('rest')
        .insert(req.body)
        .then((dados) => {
            res.send(dados);
        }, next)
    
});

server.get('/show/:id', (req, res, next) => {
    
    const { id } = req.params;

    knex('rest')
        .where('id', id)
        .first()
        .then((dados) => {
            if(!dados) return res.send(new errs.BadRequestError('nada foi encontrado'))
            res.send(dados);
        }, next)
        
});

server.put('/update/:id', (req, res, next) => {
    
    const { id } = req.params;

    knex('rest')
        .where('id', id)
        .update(req.body)
        .then((dados) => {
            if(!dados) return res.send(new errs.BadRequestError('nada foi encontrado'))
            res.send('dados atualizados');
        }, next)
        
});

server.del('/delete/:id', (req, res, next) => {
    
    const { id } = req.params;

    knex('rest')
        .where('id', id)
        .delete()
        .then((dados) => {
            if(!dados) return res.send(new errs.BadRequestError('nada foi encontrado'))
            res.send('dados excluidos');
        }, next)
        
});

2 answers

1

The mistake Possible Unhandled Promise Rejection indicates that the Promise was rejected and you did not treat this rejection. To treat rejection, make use of the try and catch:

async function makeRequest() {
  try {
    const req = await fetch(`www.asdsadasdadsadasdad.com.br`, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        data: 'data'
      })
    });
    const json = await req.json();
    console.log('JSON:', json);
  } catch (error) {
    console.error(error)
  }
}

makeRequest();

In your specific case, your role checkToken (no React Native) is performing a POST at endpoint /, and on the server is only set a GET to the endpoint /, then the request was not met.

0

What error is being returned?

Try to use fetch this way

fetch(`${BASE_API}/create`,{
    method:'post',
    headers:{
      'Content-Type':'application/json',
    },
    body:JSON.stringify({
      academia:a1,
      usuario:a2,
      senha:a3
    })
})
.then(res => res.json())
.then(res =>{
  console.log(res) <-- veja se retorna os dados do usuário logado/cadastrado
})

a1, a2 and A3 would refer to each state created by you, you know, that useState('')

const [a1, setA1] = useState('')
const [a2, setA2] = useState('')
const [a3, setA3] = useState('')

Browser other questions tagged

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