Vue agent is a complete solution to cross domain problems and a configurable linking solution along the way

Time:2021-4-14

Background: previous work requires me to write both the front and back ends, so I am used to dealing with cross domain problems in the back end. Recently, due to project problems, we need to help other groups build the front end, so we need to solve the cross domain problem of Vue programs. But on the Internet to find solutions are a bit one-sided, in the overall solution, so write an integrated version of the solution. The content may be too long or redundant, and you want to use it as needed.

0. Cross domain problems

When a browser requests the resources of another domain name from the web page of one domain name, the domain name, port and protocol are all cross domain. In the case of back-end processing, it will generally judge whether to allow the call according to the request, and add it in the response headerAccess-Control-Allow-Origin, so that illegal services can’t get my data.
Originally quite perfect, but in real work, cross domain is the browser’s strategy, data can be obtained, but the browser is not allowed to use, it has nothing to do with the background. After all, the background has given the data to you, you are useless!
Vue agent is a complete solution to cross domain problems and a configurable linking solution along the way

Moreover, the uneven level of developers makes this problem even more wrangling. Moreover, if other users are really not allowed to access, the background can directly judge how good the domain name returns error, which is no more than 100 times of cross domain security.
The cross domain problems are as follows
Vue agent is a complete solution to cross domain problems and a configurable linking solution along the way

1. Why can agents solve cross domain problems

Proxy is a service. The function of the service is to monitor the local interface. When the interface needs to access the Internet, the proxy will visit the interface for you and return the return value to the current web page.
Vue agent is a complete solution to cross domain problems and a configurable linking solution along the way
It is not the web service access agent, but the agent detects the internal interface service of the web service. When the qualified service appears, the agent blocks it and returns the result instead of the web service

2. Configuration scheme of test environment agent

In the test environment, the proxy is done with the help of webpack. Most of the online query solutions are configuration methods of this part. (probably most people just deal with cross domain problems in the process of development, and they don’t need to participate in the deployment.)
Here’s my proxy configuration. You can query webpack or online solutions for details.

proxy: {
      "/api": {
        target: " http://192.168.146.49 : 8081 ", // interface address
        Ws: true, // enable WebSockets
        Changorigin: true, // cross domain origin source 127.0.0.1:9000 allowed
        pathRewrite: {
          "^ / API": "// use this / API prefix when requesting
        }
      }
    }

So what does this mean?
When a web page is visited
Localhost: 8080 / API / xxxxx / xxx interface
Webpack will recognize this as an external interface and access it
http://192.168.146.49:8081/xxxxx/xxx
And return the result (at the beginning, I naively thought that after configuring the agent, the previous program homology problem would be solved automatically, but it was not easy to use. I thought it was a wrong configuration.)
Therefore, the access part of Axios also needs to be modified, because in the past, Axios directly accessed the corresponding address, not the local address (I didn’t understand it at first, and no one said that Axios needed to be modified after looking for it for a long time. I seriously doubt that many people get ready-made programs and only need to modify the local proxy address, so I didn’t mention this part at all.)
Before revision

import axios from "axios";
import Vue from "vue";
// import qs from "qs";

axios.defaults.withCredentials = false;

axios.defaults.headers . post ["content type"] = Application / JSON "; // configure request header

let BASE_URL = Vue.prototype.BASE_URL;
function getUrl() {
  return Vue.prototype.BASE_URL;
}
export const POST = (url, param) => {
  if (BASE_URL == undefined) {
    BASE_URL = getUrl();
    // let params = param;

    return axios.post(`${BASE_URL}${url}`, param).then(res => res.data);
  } else {
    // let params = param;

    return axios.post(`${BASE_URL}${url}`, param).then(res => res.data);
  }
};

After modification

import axios from "axios";

const BASE_URL = "/api";
axios.defaults.withCredentials = false;

axios.defaults.headers . post ["content type"] = Application / JSON "; // configure request header

export const GET = (url, param) => {
  return axios.get(`${BASE_URL}${url}`, param).then(res => res.data);
};

export const POST = (url, param) => {
  return axios.get(`${BASE_URL}${url}`, param).then(res => res.data);
};

Before the modification, about base_ URL operation, before the service dynamic configuration service address scheme. After using the proxy, this part no longer needs to be done (corresponding to the actual interface address through the proxy).
Axios when accessing / API / XX / xxx,
The address of the web page will be added localhost:8080/api/XX/xxx
And under the proxy of webpack, replace with
http://192.168.146.49Results of: 8081 / XX / xxx

3. Configuration scheme of agent in server environment

In the local debugging, webpack helps you to do the dirty work. After packaging, there is no webpack on the server. What should the agent do? After a query, ngnix is the most popular solution on the Internet. It is simple, practical and lightweight. In the future, it can be used for load balancing, so we use it instead of others.
Vue agent is a complete solution to cross domain problems and a configurable linking solution along the way
How lightweight is ngnix? Download it, change the configuration file, double-click to run OK
Vue agent is a complete solution to cross domain problems and a configurable linking solution along the way
Among them, nginx-1.16.1 confnginx.conf This is the configuration file
There’s a server brace in it,

listen       90;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
    Root e:: dist; # the packed dist of Vue project
        location / {
           try_ Files $URI $URI / @ router; # you need to point to the following @ router; otherwise, the route of Vue will be refreshed in nginx and 404 will appear
            index  index.html index.htm;
        }
        location @router {
            rewrite ^.*$ /index.html last;
        }
    location /api {
           Rewrite ^. + API /? (. *) $/ $1 break; # optional parameter, regular verification address
            include  uwsgi_ Params; # optional parameter. Uwsgi is the communication protocol between server and server application, which specifies how to forward and return requests to application
            proxy_ pass    http://192.168.146.49 ὣὣ here is your own address
        }

Listen is the port after deployment, which cannot conflict with other programs
server_ Name is the URL after deployment
Root is the packaged file location of the Vue program
The routing @ location is the configuration item of the router
Location / API is the agent of ngnix. It has the same meaning as test environment.
After all configuration, click ngnix.exe The program will start.

4. Along the way to solve the problem of configurable link, and the previous configurable solution

Our previous products need to be deployed to multiple sites due to productization, so the interface address corresponding to the service can be modified. So I wrote a base in the configuration file_ URL and exists when the project is started Vue.prototype.BASE_ In URL
The code is as follows

axios.get("./config.json").then(res => {
  //Base address
  Vue.prototype.BASE_URL = res.data.BASE_URL;
  new Vue({
    router,
    store,
    render: h => h(App)
  }).$mount("#app");
});

When calling Axios, the scheme already has it, so it will not be pasted
I thought the plan was perfect. But after configuring the agent, it suddenly occurred to me. In future deployment, you don’t just need to modify the agent’s address directly in the ngnix configuration file. Just restart ngnix. Now I want to know why I found configurable base before_ The URL scheme is so few, because when using the proxy, it is a pseudo requirement.
Write it down. I really feel that there is no end to learning. There are still many places I don’t understand. I need to increase my knowledge reserve in the future.

Recommended Today

Review of SQL Sever basic command

catalogue preface Installation of virtual machine Commands and operations Basic command syntax Case sensitive SQL keyword and function name Column and Index Names alias Too long to see? Space Database connection Connection of SSMS Connection of command line Database operation establish delete constraint integrity constraint Common constraints NOT NULL UNIQUE PRIMARY KEY FOREIGN KEY DEFAULT […]