Since contacting the front end, we are learning the essence of the leaders in the nuggets community. A short article may be someone else’s summary of the output for a long time. As a reader, we can learn some new knowledge points more quickly and comprehensively. Starting from this article, I will also write a blog in the Nuggets community to record my learning summary and start my nuggets journey with a rigorous attitude.
For my first nuggets blog post, I wanted to look at cross-domain. What is cross-domain? How to solve cross-domain problems? These are two questions that are frequently asked. Although it is theoretically possible to answer this question, it is difficult to meet cross-domain problems in a project. Today this article is suitable for young people like me to read. In the process of the interview can be cross-domain principles and common solutions to speak out, for this interview must be a plus.
After learning the passage, we can answer the following questions
-
What is cross-domain?
-
The generation and significance of cross-domain problems
-
CORS cross-domain resource sharing
-
Resolve cross-domain requests
-
How to use proxyTable to solve cross-domain development environment
In the past, our front end did not separate the era, we only need to write the most basic HTML, CSS, and then send the file to the background developers. We all use the server to render, so that the front-end and the server code is completely together, in the same Web server, the same service does not have the problem of cross-domain.
Later, as the front-end developed rapidly and we wanted to implement asynchronous, no refresh operations, we started using Ajax to implement asynchronous, no refresh operations, and the results were amazing. In this case, the deployment also put the front-end code and the server code on the same Web server, which didn’t cause cross-domain problems. This policy is the same domain name, protocol, and port. Homology requires that front-end developers also need to use a back-end compiler, such as Eclipse, to develop front-end code on their own.
What is cross-domain?
Cross-domain is actually also called a non-same-origin policy request. When we talk about cross-domain issues, we have to first understand what is the same origin policy?
Same-origin policy: It is a well-known security policy developed by Netscape. This strategy is now used by all browsers that support JavaScript. Same name means same domain name, same protocol, same port.
Domain name, protocol, port, all is same, same one different is * * * * web cross-domain server: http://127.0.0.1:3000/index.html interface address: In this project, http://127.0.0.1:4000/list domain name is the same, the same protocol, port number, across domainsCopy the code
Cross-domain solutions:
1. JSONP implementation across domains
Principle: The principle of JSONP cross-domain implementation is that the cross-domain server puts the data required by the client into a local JS method of the client and calls it, and the client processes the returned data in the local JS. This enables communication between two sites under different domain names.
Callback =fun function fun(){// Callback =fun function fun(){// Callback =fun function fun(){ Func ={callback ={… } return func(+ json.stringify (data)+); JSONP requires server-side support
Script, IMG, link, and iframe tags can cross domains
The following code, for example, can access both its own and cross-domain.Copy the code
Client request: <! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial - scale = 1.0 "> < script SRC =" https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js "> < / script > <title>Document</title> </head> <body> </body> <script> //jquery supports jSONP request $. Ajax ({// send ajax URL: 'http://127.0.0.1:8001/list', / / request address method: 'get', / / the way requests can be get, which is the json one disadvantage of cross-domain dataType: 'jsonp', //=> execute jsonp request success: res => {console.log(res)}})Copy the code
Let express = require('express'), app = express(); app.listen(8001, _ => { console.log('OK! ')}) app.get('/list', (req, res) => {let {callback = Function. Prototype} = req.query; Callback = {code: 0, Meg: callback = {code: 0, Meg: Res.send (' ${callback}(${json.stringify (data)})})Copy the code
http://127.0.0.1:8001/list?callback=jQuery214085466902496328_1593939725240&_=1593939725241 sent a list request, pass a callback function, This function is a random global function created for us by jquery. The random global function created by jquery wraps around our data, and when our browser gets the result, it executes the global function. The global function will do the SUCCESS execution for us by default, passing the data to the RES.Copy the code
Jquery does this for us:
- Jquery creates a global function by default
- Create script for us by default and send a request to our server,
- Execute success to retrieve our data when executing global functions by default.
2. CORS is cross-domain
Cross-origin Resource Sharing (CROS) Cross-source Resource Sharing.
CROS allows browsers to make XMLHttpRequest requests to cross source servers, overcoming the limitation that Ajax cannot cross source requests 🚫. CROS communication is primarily on the server, where cross-domain requests can be made as long as the server implements the CROS interface.
To support CORS Access, the server must add access-Control-allow-Origin to the response header, using * to indicate that all domains are allowed cross-domain Access.Copy the code
Details you can refer to nguyen other teachers this article: www.ruanyifeng.com/blog/2016/0…
3. Vue project development uses proxyTable to solve the cross-domain development environment
This is what I want to focus on, because the front end page of the company is realized based on VUE. When the front end is developed using vUE – CLI scaffolding vUE project, the project itself needs to occupy a port to start local services. When we intertune with the back-end server interface, we are bound to have cross-domain problems. Most companies adopt a development model of front – and back-end separation, which inevitably leads to cross-domain development. We try to solve cross-domain problems on the front end and avoid changing the back-end code.
Many projects now use WebPack automation to build front-end projects, and in WebPack projects we use ProxyTable for cross-domain implementation. ProxyTable implements cross-domain principle:
ProxyTable uses HTTP-proxy-Middleware, which is HTTP proxy middleware. The index.js file we found in the config folder at the root of the projectCopy the code
(1) Build a VUE project using vuE-CLI scaffolding
The following steps are based on you have installed the nodejs, NPM, (taobao can install a global mirror CNPM speed will be faster) NPM install CNPM – g – registry=https://registry.npm.taobao.org
Steps:
CNPM install -g vue-cli // Global installation vue-cli
- CD into the folder where you want to place the project
- Execute vue init Webpack in the current folder
CNPM I // Install dependency packages
NPM run dev // Executes the project
- So far we have set up the VUE project using VUE-CLI
(2) Configure cross-domain
Open the index.js file under the config folder of the vue project and fill in the proxyTable object with the API to be proxied.
ProxyTable: {/ / configuration specific request agent to the corresponding API interface / / interface/HomeApi be agent to http://10.64.61.129:3000/home "/ HomeApi" : {target: "Http://10.64.61.129:3000/home", / / the target address changeOrigin: true, / / whether open proxy pathRewrite: {' ^ / HomeApi ': '}}, an excuse / / request/details by proxy to http://10.64.61.129:3000/details "/ DetailsApi" : {target: "Http://10.64.61.129:3000/details", / / the target address changeOrigin: true, pathRewrite: {' ^ / HomeApi ':'}},},Copy the code
Note: The interface used to be /payment/list. To match the proxy address, we add /HomeApi in front of it, which can be distributed to /HomeApi, so we need to write /HomeApi/payment/list as the interface address. Assigned to the specified proxy, we rewrite the path by writing pathRewrite:{‘^/HomeApi’: “} to remove the /HomeApi we added earlier to match the proxy.
Reference: www.cnblogs.com/gpd-Amos/p/…
Reference: www.cnblogs.com/liyuspace/p…