I. Development scenario

In the process of middle and background front-end development, there is a scene like this: the local development environment through the proxy way to adjust the interface of the test environment; In order to retrieve the test environment interface data, you need to copy the test environment login state (Cookie) into the local development environment.

Ii. Existing programs

  1. Manually planting cookies,document.cookie='uploadticket=NhXfYIYXjmdcZNqped2Pfzc4ay8kvGWLFCoeWigy5Qs=; expires=Tue, 10 Mar 2022 10:03:55 GMT'
  2. Browser plugins grow cookies, ModHeader and other plugins.

Three, deficiencies

The existing two schemes can achieve the corresponding purpose, but the deficiency is that it needs to operate the login and copy the corresponding Cookie manually. Meanwhile, there is also the memory cost, and the whole process is still boring and annoying.

Fourth, the fundamental way

  1. Implementation principle: inwebpack-dev-serverAdded the corresponding configuration in proxy configuration, and added the login state of the test environment when forwarding requests.
  2. An example of proxy configuration is as follows: The onProxyReq configuration item is not mentioned in the document. You can find the proxy type in the HTTP-proxy-Middleware module.
import onProxyReq from '.. /scripts/on-proxy-req';

export default {
  '/app/api': {
    target: 'http://test.xxx.com/'.changeOrigin: true.pathRewrite: {},
    onProxyReq: onProxyReq
  }
};
Copy the code

Fifth, the overall plan

  1. Request the login interface of the test environment, obtain the login state (Cookie), and write the login state information to the local file.
const request = require('umi-request').default;
const cookieFilePath = require('./cookie-file-path');
const utils = require('./utils');
const fs = require('fs/promises');

try {
  const json = require(cookieFilePath);
  if (json.expires > Date.now()) {
    // console.log('Cookie information is not invalid ');process.exit(); }}catch (err) { }

request.post('http://test.xxx.com/signinSpa', {
  data: {
    username: 'admin'.password: 'admin'
  },
  requestType: 'form'.getResponse: true.timeout: 3e3,
}).then(({ response }) = > {
  // File contents
  const data = {
    cookies: {},
    expires: Date.now() + 3 * 24 * 60 * 60 * 1000
  };

  response.headers.forEach((value, key) = > {
    if (typeof key == 'string' && key.toLowerCase() == 'set-cookie') {
      const cookie = utils.parseSetCookie(value);
      if (Object.keys(cookie).length > 0) { data.cookies[cookie.name] = cookie.value; }}}); fs.writeFile( cookieFilePath,JSON.stringify(data, null.'\t')
  ).then(() = > {
    console.log('File write succeeded');
  }).catch(() = > {
    console.error('File write failed');
  });
}).catch(err= > {
  console.error(err);
});
Copy the code
  1. Read the test environment login state information from the file, and then add the login state information to the head of the proxy request.
const cookieFilePath = require('./cookie-file-path');
const utils = require('./utils');
let json = {};

try {
  json = require(cookieFilePath);
} catch (err) { }

/ / look here
function onProxyReq(proxyReq) {
  if (Object.keys(json).length > 0) {
    let cookies = proxyReq.getHeader('Cookie');
    cookies = typeof cookies == 'string' ? utils.parseCookie(cookies) : {};
    cookies = Object.assign({}, cookies, json.cookies);
    cookies = utils.stringifyCookieObj(cookies);
    proxyReq.setHeader('Cookie', cookies); }}module.exports = onProxyReq;
Copy the code
  1. Automatic processing:

Add a front command to NPM scripts, and then start local development.

{
  "scripts": {
    "start": "node ./scripts/build-cookie-file.js && cross-env BABEL_CACHE=none UMI_ENV=local umi dev",}}Copy the code

Import the corresponding method in the proxy configuration file.

import onProxyReq from '.. /scripts/on-proxy-req';

export default {
  '/app/api': {
    target: 'http://test.xxx.com/'.changeOrigin: true.pathRewrite: {},
    onProxyReq: onProxyReq
  }
};
Copy the code
  1. Run it directly at development timenpm run startDo not care about the test environment login state.