[英]How can I test express server with supertest in next.js?
[英]How to pass something like visitor hits from server (express.js) to next.js?
我已經創建了一個簡單的 next.js 應用程序並為它提供了 express.js 的后端,現在我想要的是每當有人訪問該站點時,一次命中應該來自服務器,並且服務器應該將命中數傳回給下一個.js 應用程序。 server.js 文件的代碼在這里:
const express = require("express"); const next = require("next"); var counter = 0; const dev = process.env.NODE_ENV !== "production"; const app = next({ dev }); const handle = app.getRequestHandler(); app .prepare() .then(() => { const server = express(); server.get("*", (req, res) => { counter++; return handle(req, res); }); server.listen(3000, (err) => { if (err) throw err; console.log("> Ready on http://localhost:3000"); }); }) .catch((ex) => { console.error(ex.stack); process.exit(1); });
如此處所示,我已將計數器變量設置為零,並希望在發出獲取請求時將其增加(因此在 server.get 函數中編寫了 counter++),但如何在訪問者正在訪問的路線上顯示此點擊次數?
您可以使用 express 的res.locals
來傳遞請求對象上的數據。
app
.prepare()
.then(() => {
const server = express();
server.get('*', (req, res) => {
counter++;
res.locals.counter = counter;
//----^
return handle(req, res);
});
server.listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
然后這個請求對象將在所需頁面的getInitialProps
中可用。
// some-page.js
const Page = ({ counter }) => <div>{counter}</div>;
Page.getInitialProps = ({ req, res }) => {
if (res) {
// this means that you are on the server
return { counter: res.locals.counter };
}
return {};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.