node.js - 如何使用 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 中创建时没有错误:
解决方案
您应该调用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 })
})
推荐阅读
- javascript - 导航栏上的下拉菜单在 Safari 中不起作用,但在 Chrome 中起作用
- jenkins - Jenkins Groovy,Jenkins DSL 脚本
- c++ - 基于 CLRS 的合并排序 C++ 上的算法介绍,带倒数计数
- math - 十六进制(数字)所需的数学指导
- python - 在熊猫数据框中为给定的列值创建顺序 ID
- reactjs - 在 React 中对 props 的属性进行 Props 验证
- django - 如何在外部 python 脚本 django 中导入模块
- craftcms - 如何添加资产字段
- php - PHP - 在 3 维数组中循环提供有线输出
- google-apps-script - 从一个电子表格更新到另一个电子表格时附加多行