user11119814
user11119814

Reputation:

How to make GET request with MERN Stack

I'm trying to fetch data from database. Everything I got from response is this:

Response {type: "cors", url: "http://localhost:5000/products/", redirected: false, status: 200, ok: true, …}

I need help for how to make the request in frontend and backend:

Here is ReactJS side:

getProducts() {
        fetch('http://localhost:5000/products/', {
            method: "GET",
        })
        .then(response => console.log(response))
        .then((response) => {
            console.log(response.data)
            this.setState({products: response.data});
        })
        .catch((error) => {
            console.error(error);
        });
    }

Here is my server side for the request:

router.get('/', (req, res) => {
    productService.getAll(req.query).then(products =>{
        res.status(200).json(products)
    }).catch(() => res.status(500).end())
})

Here is the productService:

async function getAll(query) {
    let products = await Product.find({}).lean()

    return products;
}

P.s.: the products are creating without errors in MongoDB Compass:

enter image description here

Upvotes: 0

Views: 1595

Answers (1)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11905

You should call response.json() to extract the JSON body from the response stream and return it to the next then block in the chain. And you can omit the method configuration since it is GET by default.

fetch('http://localhost:5000/products/')
  .then((response) => response.json())
  .then((products) => {
    this.setState({ products })
  })

Btw, you shouldn't hardcode the API URL. Use environment variables. If you're using Create React App, you can add environment variables prefixed with REACT_APP_ to .env or you can use dotenv-webpack if you have a custom Webpack setup.

fetch(`${process.env.BASE_API_URL}/products`)
  .then((response) => response.json())
  .then((products) => {
    this.setState({ products })
  })

Upvotes: 1

Related Questions