我使用 express 創建了一個簡單的 API,并將其部署到 Heroku,這是它的代碼:
const express = require("express");
const app = express();
const cors = require("cors");
app.use(express.json());
app.use(cors());
app.use(express.static("build"));
let notes = [
{
id: 1,
content: "HTML is easy",
date: "2022-05-30T17:30:31.098Z",
important: true,
},
{
id: 2,
content: "Browser can execute only Javascript",
date: "2022-05-30T18:39:34.091Z",
important: false,
},
{
id: 3,
content: "GET and POST are the most important methods of HTTP protocol",
date: "2022-05-30T19:20:14.298Z",
important: true,
},
];
const generateId = (arr) => {
const maxId = arr.length < 0 ? 0 : Math.max(...arr.map((item) => item.id));
return maxId 1;
};
app.get("/", (req, res) => {
res.send(`<h1>Hello World!</h1>`);
});
app.get("/api/notes", (req, res) => {
res.json(notes);
});
app.get("/api/notes/:id", (req, res) => {
const id = Number(req.params.id);
const note = notes.find((note) => note.id === id);
if (note) {
res.json(note);
} else {
res.status(404).end();
}
});
app.delete("/api/notes/:id", (req, res) => {
const { id } = Number(req.params);
notes = notes.filter((note) => note.id !== id);
res.status(204).end();
});
app.post("/api/notes", (req, res) => {
const body = req.body;
if (!body.content) {
return res.status(400).json({
error: "Content Missing",
});
}
const note = {
content: body.content,
important: body.important || false,
date: new Date(),
id: generateId(notes),
};
notes = notes.concat(note);
res.json(note);
});
app.put("/api/notes/:id", (req, res) => {
const newNote = req.body;
notes = notes.map((note) => (note.id !== newNote.id ? note : newNote));
res.json(newNote);
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
如您所見,提供給前端(一個 React 應用程式)的資料來自 '/api/notes' 端點,該端點回傳帶有 notes 陣列的回應。
在部署到 Heroku ( https://fierce-chamber-07494.herokuapp.com/ ) 后,添加注釋和設定重要性的功能一切正常,但我沒想到的是資料即使在重繪 頁面,在另一個設備上訪問它等等。資料只來自一個變數,而不是一個資料庫,什么都沒有。那么它為什么會持久呢?Heroku 會修改變數本身嗎?這是如何運作的?
uj5u.com熱心網友回復:
Express 服務器的頂級代碼通常在您啟動服務器時運行一次。如果有任何參考它們的處理程式,則在該頂層宣告的變數是持久的。
考慮使用 JavaScript 的客戶端頁面是如何作業的——頁面加載,然后 JavaScript 運行。如果您將選項卡保持打開幾個小時然后再回傳,您會看到在頁面加載時宣告的變數在您回傳時仍然存在。這里發生了同樣的事情,除了持久化環境在您的服務器上,而不是在客戶端的頁面上。
啟動 Express 服務器的代碼 - 即您的
const express = require("express");
const app = express();
const cors = require("cors");
app.use(express.json());
app.use(cors());
...
以及它下面的所有內容 -每次向服務器發出請求時都不會運行。相反,它在服務器啟動時運行一次,然后在發出請求時呼叫請求處理程式 - 例如內部的回呼
app.get("/", (req, res) => {
res.send(`<h1>Hello World!</h1>`);
});
因此,在頂層宣告的變數是持久的(即使跨不同的請求),因為該服務器環境是持久的。
也就是說 - Heroku 需要記住的一點是,使用他們的免費和便宜的套餐,如果在一段時間內(可能是 30 分鐘)沒有向您的應用發出請求,Heroku 基本上會通過關閉測功機來關閉您的服務器直到發出另一個請求,此時他們將再次啟動您的服務器,這將再次運行頂級代碼。因此,雖然您有時會看到一個頂級變數,其變異值似乎在多個請求中持續存在,但如果您的 Heroku 計劃不能保證您的服務器 100% 正常運行時間,那么這不是可以指望的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495424.html
下一篇:Heroku上的主機服務器
