提问者:小点点

如何用MERN堆栈发出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())
})

以下是ProductService:

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

    return products;
}

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


共1个答案

匿名用户

您应该调用response.JSON()从响应流中提取JSON主体,并将其返回到链中的下一个then块。并且可以省略方法配置,因为默认情况下它是get

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

顺便说一句,您不应该硬编码API URL。使用环境变量。如果您使用的是Create React应用程序,则可以将以react_app_为前缀的环境变量添加到.env中,如果您有自定义Webpack设置,则可以使用dotenv-webpack。

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