如何使用 MERN 堆栈发出 GET 请求
How to make GET request with MERN Stack
我正在尝试从数据库中获取数据。我从回复中得到的一切都是这样的:
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 正文并将其 return 到链中的下一个 then
块。您可以省略 method
配置,因为它默认为 GET
。
fetch('http://localhost:5000/products/')
.then((response) => response.json())
.then((products) => {
this.setState({ products })
})
顺便说一句,您不应该对 API URL 进行硬编码。使用环境变量。如果您使用 Create React App, you can add environment variables prefixed with REACT_APP_
to .env
or you can use dotenv-webpack 如果您有自定义 Webpack 设置。
fetch(`${process.env.BASE_API_URL}/products`)
.then((response) => response.json())
.then((products) => {
this.setState({ products })
})
我正在尝试从数据库中获取数据。我从回复中得到的一切都是这样的:
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 正文并将其 return 到链中的下一个 then
块。您可以省略 method
配置,因为它默认为 GET
。
fetch('http://localhost:5000/products/')
.then((response) => response.json())
.then((products) => {
this.setState({ products })
})
顺便说一句,您不应该对 API URL 进行硬编码。使用环境变量。如果您使用 Create React App, you can add environment variables prefixed with REACT_APP_
to .env
or you can use dotenv-webpack 如果您有自定义 Webpack 设置。
fetch(`${process.env.BASE_API_URL}/products`)
.then((response) => response.json())
.then((products) => {
this.setState({ products })
})