【问题标题】:How to make GET request with MERN Stack如何使用 MERN Stack 发出 GET 请求
【发布时间】:2021-03-19 16:42:38
【问题描述】:

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

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

P.s.:产品在 MongoDB Compass 中创建时没有错误:

【问题讨论】:

    标签: node.js reactjs mongodb express mern


    【解决方案1】:

    您应该调用 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,你可以使用add environment variables prefixed with REACT_APP_ to .env,或者如果你有自定义的Webpack设置,你可以使用dotenv-webpack

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

    【讨论】:

    • 谢谢,你几乎解决了。我不得不删除“.data”:D 谢谢
    • @YoanIvanov 我的错。刚刚更新了答案。
    猜你喜欢
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多