Cross domains – understand the nature of it step by step through code
Cross-domains will be encountered in both daily work and interview. The Internet is full of various materials, but most of them focus on theories without the support of actual codes. This article starts from codes, and gives cross-domain explanation with light theory and emphasis on practice.
We will use KOA to set up a local server :http://127.0.0.1:3200. Start the local client with Webpack :http://127.0.0.1:3000. Explore how a front – and back-end split project supports CORS(cross-domain resource sharing). I put the complete code on Git, read readme to get the correct posture. The main content of the article is as follows:
- Cross-domain basics
- Koa sets up the server
- Kao middleware handles cross-domain
Cross-domain basics
About the basic knowledge of cross-domain, Teacher Ruan Yifeng has a blog: Cross-domain Resource Sharing CORS detailed introduction is very clear, next I briefly introduce some theoretical knowledge through pictures and pictures.
The same-origin policy
The opposite of cross-domain is homology. The protocol, host, and port are the same.
In this example, the port is different, so we will encounter familiar errors when the customer service requests.
Access to the XMLHttpRequest at 'http://127.0.0.1:3000/user' from origin 'http://127.0.0.1:3200' has had been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Copy the code
Two requests and CORS strategies
Knowing the same origin policy, let’s talk about requests. Requests can be complex or simple. The two request browser policies are also different. Here are some examples of two types of requests:
- Simple request: The request mode is GET/POST
- Complex request: request methods are PUT or DELETE, or content-Type fields are of Type Application/JSON
The cross-domain policy for simple requests is shown below
- The client sends a simple request
- The request header field Origin indicates the source
- The server receives the request and sets the access-Control-allow-origin field in the response header to tell the customer service whether the resource is available (* indicates that all sources are available).
- Cross-domain resource sharing is complete
The cross-domain policy for complex requests is shown below
- The client initiated a complex request. Procedure
- For complex requests, send a precheck request in the form options
- Set access-Control-allow-origin, access-Control-allow-methods, and access-Control-allow-headers for the server to accept the precheck request
- Three fields tell the client which sources are allowed to cross domains, which request methods are allowed to cross domains, and which request headers are allowed to cross domains.
- The client gets the appeal information and decides whether the conditions are met. If the conditions are met, a formal request is sent. The cross-domain request is successful.
Code implementation
Knowing the above theoretical information, let’s go into practice. Look at how koA code should be written.
The service side
Start by setting up a simple server using koA/KoA-Router.
Const Koa = require(' Koa ') const Router = require('koa-router') const Router = new Router() const app = new Koa() Router.get ('/name', async (CTX) => {ctx.body = {name: 'miujg', age: 16}}) app.use(router.routes()) app.use(router.allowedMethods()) ()=>{ console.log('serve start on 3000') })Copy the code
Simple KOA server with exposed interfaces.
The client
My client here is a service started with webpack, webpack-dev-server. The js code for initiating the request is as follows
Const axios = the require (" axios ") axios. Get (' http://127.0.0.1:3000/name '). Then (rs = > {the console. The log (rs)})Copy the code
Using AXIos to initiate requests, you can also use native Ajax
The actual effect is as follows:
Simple request middleware setup
As we know from the previous theoretical knowledge, for simple requests, if the server set access-Control-allow-Origin in the response header, it can achieve the effect.
This brings us to KOA’s middleware, whose purpose is to set the Access-Control-Allow-Origin field on the response header
The code implementation is as follows:
const Koa = require('koa') const Router = require('koa-router') const router = new Router() const app = new Koa() // Use (async (CTX, next) => {ctx.response.set(' access-Control-allow-origin ', '*') // * flag allows all sources, Router. Get ('/name', async (CTX) => {ctx.body = {name: 'miujg' } }) app.use(router.routes()) app.use(router.allowedMethods()) app.listen(3000, ()=>{ console.log('serve start on 3000') })Copy the code
Note: THE KOA middleware is sequential, and the middleware that processes across domains must come first.
The request effect is as follows:
If access-Control-allow-Origin is set in the response header, the simple request for cross-domain resource sharing succeeds.
Complex request middleware Settings
Based on the above code, we make a PUT request. Put is a complex request
Axios. Put (' http://127.0.0.1:3000/name '). Then (rs = > {the console. The log (rs)})Copy the code
Add a PUT interface to the back end
router.put('/name', async (ctx) => {
ctx.body = {
name: 'miujg--put',
age: 29
}
})
Copy the code
The actual situation is as follows:
The above test environment is Firefox, and higher versions of Google Chrome have been optimized to hide option requests
Add access-Control-allow-methods to the options response header. Let’s modify the middleware:
app.use(async (ctx, next) => {
ctx.response.set('Access-Control-Allow-Origin', '*')
if(ctx.request.method == 'OPTIONS') {
ctx.status = 204
ctx.response.set('Access-Control-Allow-Methods', ['GET', 'PUT', 'POST', 'DELETE'])
ctx.response.set('Access-Control-Allow-Headers', ['Content-Type', 'Accept'])
}
next()
})
Copy the code
We intercept the options request in the middleware and set the corresponding fields.
The browser looks like this:
Note: The value of the response header may be different for different complex requests.
Now that we’ve figured out how to handle cross-domains at the code level, all we need to do in real development is introduce KOA-CORS. I won’t tell you much here.
summary
In order to understand cross-domain, it is necessary to have a clear understanding of the theoretical knowledge and how cross-domain resource sharing by browsers is a strategy. Then emulate the client and server locally and view the effect in firefox. I believe that with the process of coding, you can understand cross-domains better.