Front-end necessary skills--about cross-domain (cross-origin) problems and solving cross-domain problems

What is cross-domain/cross-origin?

What does cross-domain mean? What does cross-origin mean? It seems that I have only heard of cross-domain but not cross-origin. In fact, these two are the same thing

The cross-domain problem refers to the problem that different sites cannot call each other using ajax. The essence of the cross-domain problem is a protection mechanism of the browser. Its original intention is to ensure the safety of users and prevent malicious websites from stealing data. This is what we often call the same-origin policy (protocol, domain name, port are the same origin)

The same-origin policy is a protection mechanism, so non-same-origin is cross-origin

But this protection mechanism also brings new problems. Its problem is that it also hinders the normal calls between different sites.

When the browser sends a request to the server, any one of the protocol, domain name, and port is different, which will trigger the browser's protection mechanism

Specific errors that may occur

  • Storage content such as Cookie, LocalStorage, IndexDB cannot be read

  • DOM node unreachable

  • The Ajax request was sent, but the response was intercepted by the browser

Note: The cross-domain problem is not a problem with your Ajax, but that after the request is sent, it should be that different source browsers will automatically intercept your response

At this time, the browser will think that your computer has a virus or has been stolen by other users, so it will intercept your Ajax response. It will also report an error

 

 

The solution to cross-domain:

Note: The most fundamental and convenient way for the front-end to solve cross-domain is to communicate with the back-end classmates and let the back-end provide an interface document that supports cross-domain

There are many solutions from the big guys on the Internet. In the front-end development process, solving cross-domain problems cannot solve the problem from the root cause, but it can not affect your own development progress when the interface document is not written. You can use node.js Proxy the local server to solve its own cross-domain problems

CORS solves cross-domain:

At present, the simplest and mainstream solution to cross-domain (implemented by the front and back end together)

  • CORS: full name cross origin resource share (resource sharing)

  • Working principle: When the server returns a response message, it sets an allowed header in the response header

  • The front-end browser is above IE9, and the back-end adds the Access-Control-Allow-Origin tag to the response header to allow sites in the specified domain to access resources on the current domain.

   res.setHeader('Access-Control-Allow-Origin', '*');

  • The working process of this line of code: the browser request is sent, and the server responds, but the browser finds cross-domain access, and judges whether there is `response header: Access Control Allow Origin' (whether the backend allows cross-domain access, if allowed , the browser will leave the data, otherwise it will be discarded and an error will be reported)

 

//1. Import http module 
const http = require('http')

//2. Create a server
const app = http.createServer( (req,res)=>{
    if( req.url === '/getList' ){
        //Set Allow Cross-Origin Response Header
        res.setHeader('Access-Control-Allow-Origin', '*');
        //response json string
        res.end('{"name":"aikun"}')
    }
} )

//3. Start the server
app.listen(3000,()=>{
    console.log('The server started successfully')
})

Is there any cross-domain solution that can be completed by the front end???

Yes, the front end can use node.js to build a proxy server, and use the proxy server to send requests (cross-domain only has restrictions on browser ajax, no restrictions on nodejs)

Our nodejs server sets up an interface by itself, and allows cross-domain, and responds to the browser with data from other people's servers.

.Proxy Server Workflow

  • (1) The page sends a request to the proxy server

  • (2) The proxy server sends a request to the target server

  • (3) The target server responds the data to the proxy server

  • (4) The proxy server finally responds the data to the page

 

 

specific method:  

//1. Import http module 
const http = require('http')

// import axios
const axios = require('axios')

//2. Create a server
const app = http.createServer( (req,res)=>{
    if( req.url === '/getList' ){
        //Set Allow Cross-Origin Response Header
        res.setHeader('Access-Control-Allow-Origin', '*');
        //response json string
        res.end('{"name":"Zhang San"}')
    }else if( req.url === '/getNews' ){
        //(1) The proxy server sends a request to the target server
        /* Small details, the then formal parameter should not be called res, otherwise it will have the same name as the response message res of the above node */
        axios.get('http://c.m.163.com/nc/article/headline/T1348647853363/0-40.html').then( result=>{
            //(2) Set the allow cross-domain response header
            res.setHeader('Access-Control-Allow-Origin', '*');
            //(3) Respond the data to the page (the server needs to convert the object into JSON before it can respond)
            res.end( JSON.stringify(result.data) )
            
        } )
    }
} )


//3. Start the server
app.listen(3000,()=>{
    console.log('The server started successfully')
})

 

During the actual development process (referring to the development process, excluding packaging and launching)

Use vue-cli to solve cross domain

  1. When the vue-cli scaffolding tool starts, it will start a server for the front-end project. Users in the same local area network can all visit through the ip address.
  2. The vue-cli scaffolding supports configuring a proxy: forward the specified type of request to the target server.
  3. There is no cross-domain problem between the proxy service and the front-end service due to the unification of the protocol domain name and port, and the request can be sent directly
  4. Since the proxy service and the back-end service do not go through the restrictions of the same-origin policy of the browser, the request can be sent directly

In this way, we can forward the interface through the server proxy, and solve the cross-domain problem in the development environment. It seems complicated. In fact, vue-cli has built this technology for us, and we only need to configure it according to the requirements.

 

First configure the vue.config.js file

module.exports = {
    devServer: {
        proxy: {
            '/api': {                              //The interface that needs to be proxied
                target: 'http://39.98.***.211', //target server
                changeOrigin: true,                //Whether cross-domain
                pathRewrite: { '^/api': 'api' },   //rewrite
            },
        },
    },
}

Second, unset the base address of axios

Restart the project and verify the results

 

 

Tags: Javascript node.js Front-end Vue.js

Posted by irishmike2004 on Thu, 22 Dec 2022 23:18:10 +0300