简体   繁体   English

如何将诸如访问者命中之类的内容从服务器(express.js)传递到 next.js?

[英]How to pass something like visitor hits from server (express.js) to next.js?

I've created a simple next.js application and provide it with a backend of express.js, now all I want is whenever someone visits the site a hit should originate on the server and the server should communicate the number of hits back to next.js application.我已经创建了一个简单的 next.js 应用程序并为它提供了 express.js 的后端,现在我想要的是每当有人访问该站点时,一次命中应该来自服务器,并且服务器应该将命中数传回给下一个.js 应用程序。 The code of server.js file goes here: 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); });

as seen here I've set counter variable to zero and want it to be increased whenever a get request is made (so wrote counter++ inside server.get function) but how could I display this number of hits on the route visitor is visiting?如此处所示,我已将计数器变量设置为零,并希望在发出获取请求时将其增加(因此在 server.get 函数中编写了 counter++),但如何在访问者正在访问的路线上显示此点击次数?

You can use express's res.locals in order to pass the data on the request object.您可以使用 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);
  });

Then this request object will be available in getInitialProps of the page that is needed.然后这个请求对象将在所需页面的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM