Last week, Party A said that it would do a promotion activity on the app (in fact, let users receive OFO cycling vouchers). Considering that I have done client token verification on another app before, let’s just roll up our sleeves and do it on the previous Node directly.

  • Nuxt

This thing is similar to Next in React. It’s really handy to do Vue server rendering on Nuxt. The entire directory structure is similar to vue-CLI, but I think it’s cleaner and has a lot of configuration. This includes my favorite Loadding bar at the top, Layer theme templates, server rendering for SEO, automatic Router generation, and much more. Here I will not expand in detail, it is mainly used to choose him, and the performance is very good.

  • Express

It is a server-side tool for Koa, Egg, etc., encapsulating many convenient methods. I’m not going to go into detail here.

The first step is to complete the static page

  • Here, I will not elaborate on how to build HTML, how to use Vue and other irrelevant issues. First of all, the page effect is shown as follows:
  • After clicking “confirm”, send a request to the back end to obtain the coupon code:
  • This is the general business process.

The second step is to complete token authentication based on webView

  • How is party A’s token given to users?
    • The user logs in to the customer service
    • The user accesses the corresponding address in the WebView
    • The client binds the information such as token to the address for the server to accept and sends a GET request to the server
    • After receiving the Token, the server authenticates the user based on the Token information and returns the page to the user
  • Therefore, the Node in my hand needs to complete a Token verification requirement.

I must mention Session here. At the beginning, when I completed Token authentication, I found that when two users accessed the Token at the same time, the latter visitor would re-execute the method in the corresponding request, which is equivalent to initializing or even reassigning a lot of data. I had no idea how to separate the users. I asked my JAVA classmates and they said that the framework would separate the users by itself, which made me very depressed. In fact, they know the term Session, but they just get used to it and suddenly they don’t know what it is and they even think about it. I started with the idea of using cookies to authenticate browsers, but I always thought it was a bit old fashioned, not very fancy (personal opinion, no comment) and with limited storage. So after another day of exploring, I learned that there is a Session that validates the browser (well, cookies as data indexes). It all clicked when I knew there was such a thing.

// introduce some tools const HTTP = require('http')
const express = require("express");
const session = require('express-session'); const nuxtapp = express(); Nuxtapp. use(SESSION ({secret:'key'// Random string of 128 characters is recommended})); // Handle OPTIONS requests (Axios sends a POST request with an OPTION request to verify that the server is connected)function (req, res, next) {
  if ('OPTIONS' === req.method) {
    res.sendStatus(200);
  } else{ next(); }}); // write a Token authentication interface nuxtapp.get('/getphone', (req, res) => {
    if(! req.query.token) { //if else. res.sendStatus(200)return; } // Creating a request here is just an example. Some tokens can be resolved locally, while others require a server to request resolution from another server. Const request = http.request({host:"api.example.com",
      headers: {
        'Content-Type': ' application/json'.'Accept-Encoding': 'utf-8'// Set the encoding mode to be returned and set the others to be garbled'Accept-Language': 'zh-CN,zh; Q = 0.8 '.'Connection': 'keep-alive',
      },
      path: '/getTokenorSth',
      port: 'port',
      method: 'POST'
    }, response => {
      let data = ""; Response.on ("data".function (chunk) {
        data += chunk
      })
      response.on("end".function() {// set seesion try {if(! req.session.id) { //set session like : req.session.id= JSON.parse(data)
          }
          res.sendStatus(200)
        } catch (err) {
          console.log(err);
          res.sendStatus(500)
        }
      })
    }).on('error', (e) => {console.log(' Error message:${e.message}`); res.sendStatus(500) }); // POST Data request.write(JSON.stringify({ example:example, token: req.query.token })); Post request.end(); }) nuxtapp.listen(port || 80,'0.0.0.0')
console.log("Server started, please visit -- localhost:" + port || 80)Copy the code

The third step server agent (here I also have a point is not very sure, the so-called Taobao Node+JAVA is not this mode)

After all, I am still a front-end, so I will leave the implementation of the functional aspects to the senior JAVA (if I have time, I really want to write SQL review).

  • The user still requests Node for access. It’s important to note that if the backend provides multiple interfaces, you don’t have to write app.get(‘/API ‘) or something for each of them. The Express documentation says something like this:
nuxtapp.all(["/api1/*"."/api2/*"], requestFunction)Copy the code

The other is similar to the above token verification

Step 4 Execute Nuxt with Express

  • The Nuxt official website actually has some code to teach you how to use your own Node to run, but has not been very perfect, a little unsatisfactory. I am here to add my understanding, where write wrong, please feel free to spray, thank you spray me every person.
// nuxt
const {
  Nuxt,
  Builder
} = require('nuxt'// Introduce core build attributes // determine the development environment const isProd = (process.env.node_env ==='production') const port = process. The env. Port | | / 80 / introduce nuxt configuration const config = require ('./nuxt.config.js') config.dev = ! isProd; const nuxt = new Nuxt(config); // Determine the production mode dev(developer mode) means rebuild; Pro (production mode) means execution directly from yanr Build filesif (config.dev) {
  new Builder(nuxt).build()
    .then(listen)
    .catch((error) => {
      console.error(error)
      process.exit(1)
    })
} else {
  listen()
}Copy the code

Listen is the express server with the corresponding interface that I wrote in steps 2 and 3.

  • New nuxt returns a nuxt method after an instance of nuxt. Nuxt renders request,response, and express() in order of execution. If the get request from the code in step 2 is matched initially, then the various interfaces in the all method written after step 2 will not receive it.
  • What I consider is that interfaces are not implemented for no reason, but user requests are inevitable. So Nuxt takes over when the user sends a request except on purpose. Therefore, Nuxt will render the page last and hand it to the user. To facilitate Token verification, I put the Token verification request on the home page and let the browser capture the Token and relevant information and hand it to Node for manual login. (It is also possible to determine whether Token authentication is performed by checking the presence of tokens before nuxT rendering, but I won’t show you a lot of code here.)
  • All GET requests are captured and handed to Nuxt:
// Finally capture nuxt render nuxtapp.get('/ *', (req, res) => {
  nuxt.render(req, res)
})Copy the code

Demo: jasontan.cn Original link: github.com/A0150315/ja…

Please indicate the source of reprint.