kris_needs_help
kris_needs_help

Reputation: 71

Get JSON Object from URL using Express

In the express users.js file:

router.get('/', function(req, res, next) {
  fetch('https://www.somwhere.com/users')
      .then(res => res.json())
      .catch(error => console.log(error));
});

module.exports = router;

In my App.js file for my React App I use

componentDidMount() {
        fetch('/users')
            .then(res => res.json())
            .then(users => this.setState({ users }));
    }

Right now it throws a 500 error and its not catching the error

Can I get some help fixing this

Upvotes: 0

Views: 1010

Answers (1)

Titus Sutio Fanpula
Titus Sutio Fanpula

Reputation: 3613

You can use axios in your FrontEnd("React") and BackEnd("Express"). This code below only an example code that you can follow:

🔴 Backend: Express Server Using axios

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

app.use(cors( { origin: '*'}));

const END_POINT = 'https://jsonplaceholder.typicode.com/users';

app.get('/users', async (req, res) => {
  try {
    const { data } = await axios.get(END_POINT);
    res.status(200).send(data);
  } catch(ex) {
    res.status(500).send(ex.data);
  }
})

app.listen(3000, () => {
  console.log('Server is up');
});

The code above only an example if you want to using axios in your backend.

📤 Updated: Using fetch

If you still want to using fetch, then you can use code below 👇:

router.get('/', async (req, res) => {
  try {
    const result = await fetch('https://jsonplaceholder.typicode.com/users');
    const json = await result.json();
    res.status(200).send(json);
  } catch(ex) {
    console.log(ex);
    res.status(500).send(ex.message);
  }
})

module.exports = router;

🔵 FrontEnd: React Using axios

async componentDidMount() {
  try {
    // change the endpoint with yours
    const { data } = await axios.get('http://localhost:3000/users');
    console.log(data);
    // do some stuff here: set state or some stuff you want
  } catch(ex) {
    console.log(ex);
  }
}

💡 Dont Forget to install and import axios in your React App.

📤 Updated: If you still want to using fetch in your React App, than you can use this code below:

async componentDidMount() {
  try {
    // change the endpoint with yours
    const result = await fetch('http://localhost:3000/users');
    const json = await result.json();
    console.log(json);
    // do some stuff here: set state or some stuff you want
  } catch(ex) {
    console.log(ex);
  }
}

I hope it's can help you 🙏.

Upvotes: 2

Related Questions