首页 > 解决方案 > 如何使用 MERN Stack 发出 GET 请求

问题描述

我正在尝试从数据库中获取数据。我从回复中得到的一切都是这样的:

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

我需要有关如何在前端和后端发出请求的帮助:

这是 ReactJS 方面:

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);
        });
    }

这是我的请求服务器端:

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

这是产品服务:

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

    return products;
}

Ps:产品在 MongoDB Compass 中创建时没有错误:

在此处输入图像描述

标签: node.jsreactjsmongodbexpressmern

解决方案


您应该调用response.json()从响应流中提取 JSON 正文并将其返回到then链中的下一个块。您可以省略method配置,因为它是GET默认的。

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

顺便说一句,您不应该对 API URL 进行硬编码。使用环境变量。如果您使用的是Create React App,则可以添加以REACT_APP_to.env为前缀的环境变量,或者如果您有自定义 Webpack 设置,则可以使用dotenv-webpack 。

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

推荐阅读