我整天都在努力嘗試將我的 MERN 堆疊應用程式部署到 Heroku。到目前為止,如果我在本地運行它,它作業得很好。該應用程式部署在 Heroku 上,但是當我嘗試從 MongoDB Atlas 提交/獲取專案時,我收到 404 錯誤。
我嘗試洗掉 package.json 中的代理,但沒有奏效。我運行了一個構建命令,檔案在正確的位置,仍然無法正常作業。我真的對可能發生的事情一無所知..
這是代碼:
后端:
index.js
const express = require('express');
const app = express();
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
app.use(cors());
app.use(express.static('build'));
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb' }));
const uri =
'mongodb srv://db:[email protected]/myFirstDatabase?retryWrites=true&w=majority';
mongoose.connect(uri);
const profileSchema = new mongoose.Schema({
..
..
..
});
const Profile = mongoose.model('Profile', profileSchema);
module.exports = mongoose.model('Profile', profileSchema);
profileSchema.set('toJSON', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString();
delete returnedObject._id;
delete returnedObject.__v;
},
});
app.get('/api/profiles', (req, res) => {
Profile.find({}).then(profiles => {
res.json(profiles);
});
});
app.post('/api/profiles', (request, response) => {
const body = request.body;
if (!body) {
return response.status(400).json({
error: 'content missing',
});
}
const profile = new Profile({
...
...
...
});
profile.save().then(savedProfile => {
response.json(savedProfile);
});
});
const PORT = process.env.NODE_ENV || 3001;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
我的前端:App.js
function App() {
const [viewProfile, setViewProfile] = useState(false);
const [formState, setFormState] = useState(1);
const [prof, setProf] = useState([]);
const handleProfile = () => {
setViewProfile(!viewProfile);
};
const fetchData = async () => {
await axios.get('/api/profiles').then(res => setProf(res.data));
};
useEffect(() => {
fetchData();
}, []);
const addProfile = async data => {
let img = await ImgToBase64(data.profImg);
await axios.post('/api/profiles', {
...
...
...
});
fetchData();
alert(`success!`);
};
return (
<ChakraProvider>
...
...
...
</ChakraProvider>
);
}
我能得到一些幫助嗎?我幾乎嘗試了一切
uj5u.com熱心網友回復:
Heroku 為您提供節點的容器而不是 VPS(虛擬專用服務器)。在他們的服務器內部,有超過 1 萬個應用程式在虛擬機上運行。他們正在將您的應用程式埠映射到他們的子域。為此,您必須將埠配置提供給您的應用程式。
在您的代碼中,有process.env.NODE_ENV但在 Heroku 環境中,他們使用的是process.env.PORT。
const PORT = process.env.PORT || 3001;
此外,您需要在 package.json 中添加一個啟動腳本。
start: "node index.js"
如果你的主檔案不是 index.js,你可以用主腳本名替換你的腳本名
uj5u.com熱心網友回復:
你可以試試這兩件事。
- 更改您的埠名稱。
https://devcenter.heroku.com/articles/getting-started-with-nodejs#push-local-changes
你的代碼:
const PORT = process.env.NODE_ENV || 3001;
后
const PORT = process.env.PORT || 3001;
- 確保您在檔案中創建了帶有文本“web: npm start”的 Procfile。 https://devcenter.heroku.com/articles/getting-started-with-nodejs#define-a-procfile
檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406690.html
標籤:
