-2

I'm creating a mobile app using:

  • Front-end: react native
  • Front-end Platform: Expo
  • Back-end: nodejs
  • Database: MySQL/Sequelize
  • Http requests handler: Axios

I've a post route in back-end that executes an action to insert of date and time which the route is executed. In postman it's working fine, but when I try run this clicking in the app button is returned the axios error: Network Error.

I'm using cors module in back and I've tried replace it to a middleware that set response headers, but anything not worked.

/client/utils/api.js

import axios from 'axios'

const api = axios.create({
  baseURL: 'http://localhost:5000'
})

export default api

/client/components/pages/registrar/index.js

import React from 'react';
import { Image, StyleSheet, View, Text, Button } from 'react-native';
import { 
  Container,  
  Input,
  ButtonSubmit,
  TextButtonSubmit
} from "./styles";
import api from '../../../utils/api';
//import axios from 'axios'

const styles = StyleSheet.create({
  tamLogo:{
    width: 90,
    height: 90
  }
})

function Registrar(){
  
  function onFormSubmit(){
    api.post('/registro/registrar')
      .then((res) => {
        console.log("Entrou no then")
      })
      .catch((error) => {
        console.log(JSON.stringify(error))
      })
  }

  return(
    <Container>

      <Image
        style = {styles.tamLogo}
        source = {{uri: "https://cdn-icons-png.flaticon.com/512/17/17004.png"}}
      />

      <Input autoCapitalize="none"/>
      <Input secureTextEntry={true} />
      <ButtonSubmit onPress={onFormSubmit} >
        <Text>Registrar ponto</Text>
      </ButtonSubmit>

    </Container>
    
  )
}

export default Registrar;

/server/index.js

const express = require('express')
const cors = require('cors')
const conn = require('./db/conn')

const app = express()

app.use(express.json())
//I'm using cors module as suggested in https://stackoverflow.com/questions/45980173/react-axios-network-error
app.use(cors({
  origin: 'http://localhost:3000'
}))

// I tried this suggestion answered in https://stackoverflow.com/questions/49132636/post-request-axios-network-error

/*app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});*/

app.get('/',(req,res) => {
  res.send("Estamos no back-end do app de pontos")
})

app.use('/registro',require('./routes/RegistroRoutes'))

// conn.sync({force:true}) // resetando o banco
 conn.sync() // mantendo os dados do banco
  .then(() => {
    app.listen(5000,()=>{
      console.log("Estamos rodando o back-end na porta 5000")
    })
  })
  .catch(e => console.error('Erroooooo: ' + e))

Axios Error response in json

{
  "message":"Network Error",
  "name":"AxiosError",
  "stack":"AxiosError@http://192.168[...]",
  "config":{
    "transitional":{
      "silentJSONParsing":true,
      "forcedJSONParsing":true,
      "clarifyTimeoutError":false
    },
    "transformRequest":[null],
    "transformResponse":[null],
    "timeout":0,
    "xsrfCookieName":"XSRF-TOKEN",
    "xsrfHeaderName":"X-XSRF-TOKEN",
    "maxContentLength":-1,
    "maxBodyLength":-1,
    "env":{},
    "headers":{
      "Accept":"application/json, text/plain, */*"
    },
    "baseURL":"http://localhost:5000",
    "method":"post",
    "url":"/registro/registrar"
  },
  "code":"ERR_NETWORK",
  "status":null
}

What else can I try to run my application successfully?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
OPaulo
  • 9
  • 2

1 Answers1

-1

I think you are using localhost on your client what is wrong as your client is not in the same computer of the server. To solve you must specify the correct ip or host on api.js

import axios from 'axios'

const api = axios.create({
  baseURL: 'http://MY-SERVER-IP:5000'
})

export default api