Unhandled rejection typeerror failed to fetch

[

I’m starting in web development.
I used create-react-app to create my project.
I am able now to render different pages and to have routes between the pages which is perfect.

Now, I am trying to add the backend part of the project.
I am using express and probably will use MongoDB but I can’t figure out exactly how to manage the calls to server from client.
Here is my example :
1. in App.js I have the following, just a simple login page :

import React, { Component } from 'react';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import logo from './logo.svg';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import './App.css';
import api from './api'
import { browserHistory } from 'react-router'

class App extends Component {

  goToUsers () {
    api.login()
  }

  render() {
    return (
      <MuiThemeProvider>
        <div className="App">
          <div className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h2>Welcome to React</h2>
          </div>
          <p className="App-intro">
            To get started, edit <code>src/App.js</code> and save to reload.
          </p>
          <br />
          <br />
          <TextField hintText="Login" />
          <br />
          <TextField hintText="Password" type="password" />
          <br />
          <br />
          <RaisedButton label="Login" onTouchTap={this.goToUsers}/>
        </div>
      </MuiThemeProvider>
    );
  }
}

export default App;

the login function is supposed obviously to fetch data from the client but for now I just have a simple function in api.js where I want to centralize my api functions:

class Api {
  login () {
    fetch('localhost:3000/users')
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json()
    })
  }
}

export default new Api()

and finally the index.js

import React from 'react';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { Router, Route, IndexRoute, IndexRedirect, browserHistory, Link } from 'react-router'

import App from './App';
import Users from './users';

injectTapEventPlugin();


ReactDOM.render(
  <Router history={browserHistory}>
    <Route path="/" component={App} />
    <Route path="/Users" component={Users} />
  </Router>
  , document.getElementById('root'))

I am not copying users.js and other objects for simplicity but all classes works fine when going to http://localhost:3000/ or http://localhost:3000/users

however when I click on the button, I get the error Unhandled Rejection (TypeError): Failed to fetch.

Any idea what I am missing?

,

class App extends Component {
  constructor(props) {
    super(props);
    state = { users: null }
  }
  goToUsers() {
    //just put your request directly in the method
    fetch('http://localhost:300/users')
      .then(response => {
        //do something with response
        const users = response.json();
        this.setState({ users })
      })
      .catch(err => {
        throw new Error(err)
      })
  }

  render() {
    return (
      <MuiThemeProvider>
        <div className="App">
          <div className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h2>Welcome to React</h2>
          </div>
          <p className="App-intro">
            To get started, edit <code>src/App.js</code> and save to reload.
          </p>
          <br />
          <br />
          <TextField hintText="Login" />
          <br />
          <TextField hintText="Password" type="password" />
          <br />
          <br />
          <RaisedButton label="Login" onTouchTap={this.goToUsers}/>
        </div>
      </MuiThemeProvider>
    );
  }
}

,

At first, make sure the endpoint of your API is correct and the server is running successfully without any issue. You can use Postman to test your API. Once your API is running successfully then you can make a request from the front-end(react.js).

fetch('localhost:3000/users')
    .then(response => {
      if (!response.ok) {
        throw new Error(response.statusText)
      }
      return response.json()
    }).catch(err=>{
    console.log(err)
})

Use catch for handling all errors.

know more

Thank you.

,

check your server is running or not. if not run it again by using node index.js. and your server-side port should be different

,

include app.use(cors({origin: “*”,})) in your backend index.js

]

How do you fix TypeError failed to fetch?

To solve the "TypeError: Failed to fetch", make sure to pass the correct configuration to the fetch method, including the URL, HTTP method and headers, and verify that the server you're making a request to is setting the correct CORS headers with the response.

What is the meaning of Failed to fetch?

When you see an error saying "Failed to fetch" or get an ICE error this means that there is a connectivity issue between you and Lookback. Typically this is related to a firewall blocking your connection in some way.