【发布时间】:2023-03-16 02:22:01
【问题描述】:
在将我的代码上传到 Heroku 之前,我的 API 调用运行良好。但是,它在部署后返回状态码503 (Service Unavailable)。
这是我的代码
我的根文件夹中的 app.js 文件(服务器文件)
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log("Connected to db!")).catch(dbErr => console.log(dbErr));
app.use(express.json());
app.use(cors());
app.post("/post-result", async (req, res) => {
console.log(req.body.val);
const newSurvey = new survey({ surveyValues: req.body.val });
await newSurvey.save()
.then(data => {
res.send(newSurvey);
console.log(newSurvey);
}).catch(err => console.log(err));
});
app.get("/results", async (req, res) => {
const result = await survey.find({});
res.send(result);
});
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "/client/build")));
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
})
} else {
app.get("/", (req, res) => {
res.send("API running");
})
}
app.listen(process.env.PORT, () => console.log("Listening on PORT 8080"));
我的反应文件,API 调用的地方
const handleFormSubmit = async (e, val) => {
const { data } = await Axios.post("/post-result", { val });
}
package.json 文件
{
"scripts": {
"start": "nodemon app.js",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^6.0.12"
}
}
控制台中的错误日志
Uncaught (in promise) Error: Request failed with status code 503 at e.exports createError.js:16) at e.exports (settle.js:17) at XMLHttpRequest.S (xhr.js:66)
【问题讨论】:
标签: node.js api heroku mern http-status-code-503