Background In daily development, when we need to communicate with the backend, when sending interface request, the backend will check whether the interface has cookie, if not, the backend will return a redirectUrl, which is a login address on the line. Therefore, the common practice is to log in to the online system, copy the cookie, write the cookie of the local Webpack, and restart the Webpack again.

{
    /api/: {
        headers: {
           cookie: 'Cookie from the line I just logged in to'}}}Copy the code

Problems arising

  1. Currently debuggedcookieIf it fails, you need to log in again and then copycookieAnd finally restart the whole project
  2. Every time you commit code, you need to clean it upcookie【 becausecookieIt’s different every time.
  3. A lot of time was spent on this replicationcookieon

Cause analysis,

  1. The backend needs to make interface calls every timecookiecheck
  2. cookiefailureredirectUrlIt’s an online address written dead, not based onrefereTo determine the

Project research

  1. cookieDo not do failure check
  2. redirectUrlAccording to therefereTo judge
  3. Front end bywebpackThe proxy implementationcookieAuto write back

The results of

  • cookieandredirectUrlThese two solutions, for the back end of the change is very large, so it will not work
  • usewebpackAutomatic back to write
let cookie = ' '; . {/api/: {
        // This means that you want to customize the data returned
        selfHandleResponse: true.onProxyReq(proxyReq, req, res) {
            // Set cookies before each request
            proxyReq.setHeader('cookie', cookie);
        },
        onProxyRes(proxyRes, req, res) {
            if (proxyRes.headers['set-cookie']) {
              // Get the cookie returned by the backend system
              cookie = proxyRes.headers['set-cookie'].join('; ');
            }
            var body = [];
            proxyRes.on('data'.function (chunk) {
                body.push(chunk);
            });
            proxyRes.on('end'.function () {
                body = JSON.parse(Buffer.concat(body).toString());
                if(! body.success && body.code ===302) {
                  body.message.redirect = 'http://localhost:3000';
                }
                res.end(Buffer.from(JSON.stringify(body))); }); }}}...Copy the code

This approach is discussed only for point-to-point systems

This scheme will be ineffective if the following system is used

So how do you solve this?