Solve the problem of spanning different sources of requests in many aspects

Posted by johnsmith153 on Wed, 08 Dec 2021 03:32:29 +0100

Solve the problem of spanning different sources of requests in many aspects

Homology policy is an agreement. The browser was introduced by Netscape in 1995. It is the most core and basic security function of the browser. Without homology policy, the browser is vulnerable to XSS, CSFR and other attacks. The so-called homology means that "protocol + domain name + port" are the same. Even if two different domain names point to the same ip address, they are not homologous. The same origin policy limits the following behaviors:

  • Cookie s, LocalStorage, and IndexDB cannot be read
  • DOM and JS objects cannot be obtained
  • AJAX request cannot be sent

1, Agent solution in front-end development

- the IP address of the proxy server and the IP address of the requester are the same (same source) -

resolvent:

  1. In general projects, to use webpack, you need to have a webpack dev server and configure it in webpack.config.js

    devServer: {
      contentBase: 'dist',
      port: 8080,
      inline: true,
      overlay: true,
      proxy: {
        '/api': { // Proxy path
          target: 'https://baidu.com / ', / / IP address of the proxy's target server
          changeOrigin: true,
          pathRewrite: {
            '^/api': '' // Rewrite the request path to replace / api with an empty character
          }
        }
      }
    }
    
  2. On the Vue scaffold, configure it in vue.config.js

    module.exports = {
      devServer: {
        proxy: {
          '/api': {  // Proxy path
            target: 'https://misterma.com / ', / / IP address of the proxy's target server
            changeOrigin: true,
            pathRewrite: {
              '^/api': '' // Rewrite the request path to replace / api with an empty character
            } 
          }
        }
      }
    }
    
  3. On the react scaffold, configure in package.json

    • Simple usage: {proxy ":" proxy's target server IP address "} (only one target IP address can be proxy, and the front-end resources are preferentially matched)

    • Standard usage:

      1. Create a setupProxy.js configuration file in the src directory (the contents of the configuration file will be automatically integrated by the scaffold)

      2. Write setupProxy.js to configure specific proxy rules:

        // common Js specification react scaffold finds the syntax of node.js used to add the configuration file to the webpack
        const { createProxyMiddleware } = require('http-proxy-middleware') // The package scaffold is installed by default
        
        module.exports = function(app) {
            app.use(
                createProxyMiddleware('/api1', { //  The proxy configuration is triggered when a prefix request of / api1 is encountered
                    target: 'http://localhost:5000 ', / / the requested third-party interface
                    changOrigin: true, // Controls the value of the host field in the request header received by the server
                    pathRewrite: {
                        '^/api1': '' // Rewrite the request path to replace / api1 with an empty character
                    }  
                })
            )
        }
        /**
         * changOrign When set to true, the host of the request received by the server is localhost:5000
         * changOrign When set to false, the host in the request header received by the server is: localhost:3000
         */
        

2, Server settings cross domain

  1. Allow cross domain settings in nodejs (CORS protocol):

    const express = require("express");
    const app = express();
    
    //Set up cross domain access
    app.all("*",function(req,res,next){
        //Set the domain name that allows cross domain, * means that any domain name is allowed to cross domain
        res.header("Access-Control-Allow-Origin","*");
        //Allowed header types
        res.header("Access-Control-Allow-Headers","content-type");
        //Cross domain allowed request mode 
        res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
        if (req.method.toLowerCase() == 'options')
            res.send(200);  //Let options try to request a quick end
        else
            next();
    })
    
  2. nodejs server setup proxy:

    npm install --save-dev http-proxy-middleware
    
    const express = require('express')
    const { createProxyMiddleware } = require('http-proxy-middleware')
    
    const app = express()
    
    app.use('/api', createProxyMiddleware({
      target: 'http://www.example.org ', / / IP address of the proxy's target server
      changeOrigin: true, // The default is false. Do you want to change the original host header to the target URL
      ws: true, // Proxy websockets
      pathRewrite: {
        '^/api': '' // Rewrite the request path to replace / api with an empty character
      }
    }))
    
    app.listen(3000)
    
    

    The first parameter of createProxyMiddleware('/ api', optionsObj) can be omitted, and if omitted, all parameters will be matched; You can set the array to match multiple paths;

    You can also set custom matching rules for functions.

    For fine-grained matching, wildcard matching can be used:

    • createProxyMiddleware('* *', {...}) ` matches any path, and all requests will be forwarded;
    • createProxyMiddleware('* * / *. html', {...}) ` matches any request ending in. html;
    • createProxyMiddleware('/ *. html', {...}) ` matches requests ending in html in the current path;
    • createProxyMiddleware('/api/**/*.html', {...}) matches the request ending in html under / api;
    • createProxyMiddleware(['/api/**', '/ajax / * *'], {...}) combination
    • createProxyMiddleware(['/ api /', '! / bad.json'], {...}) does not include * * / bad.json`

Topics: node.js Front-end React Vue.js Webpack