我试图在heroku应用程序上部署我的MERN项目,但是当我尝试从后端服务器获取所有数据时,它在控制台中给了我这样的错误:
未捕获(承诺)错误:请求失败,状态码为404 在createError(createError.js:16) 在解决时(settle.js:17) 在XMLHttpRequest.handleLoad(xhr.js:61)
这是我的获取数据的axios:
useEffect(() => {
const fetchItems = async () => {
setLoading(true);
const res = await axios.get("/api/products");
setProducts(res.data);
setLoading(false);
};
document.title = `Shop - The Beuter`;
fetchItems();
}, [props]);
如果我添加localhost:8000/api/products
可以正常工作,但是将其部署到heroku时无法获取数据
这是我的server.js:
const express = require("express"),
bodyParser = require('body-parser'),
app = express(),
cors = require("cors"),
port = process.env.PORT || 8000,
db = "beuter",
path = require("path"),
server = app.listen(port, () => console.log(`Listening to on port ${port}`));
app.use(bodyParser.json());
app.use(cors());
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static('beuter/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'beuter', 'build', 'index.html'));
})
}
require("./server/config/database.config")(db);
require("./server/routes/product.route")(app);
这是我的database.config.js:
const mongoose = require(“ mongoose”);
module.exports = (name) => {
mongoose
.connect(process.env.MONGODB_URI || `mongodb://localhost/${name}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
})
.then(() => console.log(`Successfully connected to ${name}`))
.catch((err) => console.log(err));
};