如何解决如何使用 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;
}
P.s.:产品在 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,则可以使用 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 })
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。