【发布时间】:2022-01-23 09:09:26
【问题描述】:
我有一个 Mern 堆栈项目。它在本地主机中工作。部署到 netlify 后,我的前端出现错误。
函数报错。
axios.get('/api/getbouquets').then((response)=>{
const data = response.data;
setBouquets(data);
setHomeProducts(homeProducts => [...homeProducts, data[0]]);
}).catch(()=>{
console.log("data could not fetch from server side")
});
这是我在前端的 package.json。我使用代理连接到后端。
{
"name": "flower-shop-v4",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:8080",
"dependencies": {...
}
这是我在后端的 server.js
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config()
// Accessing the path module
const path = require("path");
const app = express();
app.use(cors());
const PORT = process.env.PORT || 8080;
const routes = require("./routes/api");
mongoose.connect( process.env.MONGODB_STRING,{
useNewUrlParser: true,
useUnifiedTopology: true
})
mongoose.connection.on('connected', ()=>{
console.log('Mongoose is connected!');
})
app.use(express.json());
app.use(express.urlencoded({ extended: false}));
app.use("/api", routes);
app.use(express.static(path.join(__dirname, '/client/build')))
app.get('/*', (req,res)=>{
res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
})
app.listen(PORT, console.log(`Server is starting at ${PORT}`));
此项目在 Heroku 中使用这些设置运行。但它不适用于netlify。顺便说一句,我查看了 MongoDB 的白名单。所有IP都在白名单中。这个问题不是因为这个。
context.js:44 是我的错误。
context.js:39 是response.data。 response.data 是我的 index.html,因为我在公用文件夹中使用了 _redirects。
_重定向
/* /index.html 200
我意识到这很愚蠢。删除重定向后,前端尝试从后端获取数据时出现 404 错误。因为它们彼此没有联系。如何连接它们?
【问题讨论】:
-
看起来您正在 Home.js 中的某个数组上切片和使用地图,这可能是一个问题。除此之外,我建议检查
response.data,因为承诺中的任何失败行都可以发送它来捕获。你也可以试试catch(e) => {console.log(e)}。分享这些控制台日志的输出 -
@boxdox 我做了他们并编辑了答案。正如你所说,由于切片方法的问题。我试过 if(boquets.length !== 0){..}。但它不起作用。你有什么主意吗?顺便说一句,它仍在 heroku 上工作。
-
需要检查 Netlify 配置文件。因为你没有提到所以不能没有它。