Several ways to solve front-end cross – domain

If you want to solve cross-domains you have to know why cross-domains occur, right

Cross-domain: means that the browser cannot execute scripts from other sites. This is caused by the browser’s same-origin policy, which is a security restriction that the browser adds to javascript. Same-origin policy is a convention that is a core security feature of the browser

The same origin policy has the following effects

  • Cookie, LocalStorage, and IndexDB cannot be read

  • DOM and JS objects cannot be retrieved

  • The Ajax request could not be sent

Whether homologous or not is mainly seen in three aspects:

  • Whether the protocols are the same (HTTP HTTPS file)
  • Check whether the host ADDRESSES are the same (www.xxx.com 127.0.0.1).
  • Port (0 to 65535) (HTTP default port is 80; The HTTPS default port is 443; MySQL default port 3306)

If the protocol, host address, and port of two urls are the same, they are homologous; otherwise, they are non-homologous.

The cross-domain solutions are as follows

JSONP

Programmers are forced to come up with cross-domain solutions.

The JSONP scenario has nothing to do with Ajax

The JSONP scheme supports only GET requests but not POST requests

JSONP has no browser compatibility issues and is supported by any browser.

The idea: A web page requests JSON data from the server by adding a

  • The principle of

    • The client requests an interface using the SRC attribute of the script tag because the SRC attribute is not cross-domain.
    • The server responds with a string
    • The client receives the string and runs it as JS code.

    Back-end interface code:

app.get("/api/jsonp".(req, res) = > {
  // res.send('hello');
  // res.send('console.log(1234)');
  // res.send('abc()')
  // res.send('abc(12345)')

  // The function name of the receiving client
  let fn = req.query.callback;
  let obj = { status: 0.message: "Login successful" };
  let str = JSON.stringify(obj);
  res.send(fn + ` (${str}) `);
});
Copy the code

Front-end code:

<script>
  // Prepare a function in advance
  function xxx(res) {
    console.log(res);
  }
</script>

<script src="http://localhost:3006/api/jsonp? callback=xxx"></script>
Copy the code
<script src="http://test.com/data.php?callback=dosomething"></script>
// make a request to the server test.com with a callback parameter in the query string that specifies the name of the callback function
 
// Process the data that the server returns from the callback function
<script type="text/javascript">
    function dosomething(res){
        // Process the obtained data
        console.log(res.data)
    }
</script>
Copy the code

jQuery ajax:


$.ajax({
    url: 'http://www.test.com:8080/login'.type: 'get'.dataType: 'jsonp'.// The request is jSONP
    jsonpCallback: "handleCallback".// Custom callback function name
    data: {}});Copy the code

Vue.js

this.$http.jsonp('http://www.domain2.com:8080/login', {
    params: {},
    jsonp: 'handleCallback'
}).then((res) = > {
    console.log(res); 
})
Copy the code

If the front end uses jquery $. Ajax ({dataType:’ jSONp ‘}), the dataTape option must be set to JSONP

The back end can simply call res.jsonp(data) with express name

Cors way

  • Nothing to do with the front end
  • Cors needs to be enabled on the backend
  • CORS stands for Cross-Origin Resource Sharing. It is a W3C standard and a fundamental solution for cross-source AJAX requests.

Essentially, you add cross-domain sources to the response header

Access-control-allow-origin: field and value (which source addresses are allowed to request this server)

Vue-cli proxy forwarding

The development environment

Cross-domain is forbidden by browser, but not by server. When running NPM run dev and other commands locally, node is actually used to run a server. Therefore, proxyTable actually sends requests to its server, and then the server forwards them to the background server.

  • If the backend jSONP is not done, cORS is not done, I will give you an interface address

  • We can get a server locally, and then use the server to request the backend server interface address

    • But vuecli scaffolding, which starts a WebPack development server, can do proxy forwarding

      • And the front end is the same source as this server with port 8080
  • You need to modify the configuration of the WebPack development server

Set up an intermediate proxy service between the front-end service and the back-end interface service, and its address remains the same as that of the front-end service, then:

  1. There is no cross-domain problem between the proxy service and the front-end service because the protocol, domain name and port are unified. The proxy service can directly send requests

  2. The proxy service and the back-end service can directly send requests without the same origin policy restriction of the browser

In this way, we can do interface forwarding through the middle server to solve cross-domain problems in the development environment. It seems very complicated, but vuE-CLI has built this technology for us. We just need to configure it as required.

devServer: {
    proxy: {
      // http://c.m.163.com/nc/article/headline/T1348647853363/0-40.html
      '/api': { // Request relative path starts with/API
        target: 'http://c.m.163.com'.// Background interface domain name The real interface address we want to proxy
        changeOrigin: true.// Change the source of the request (trick the backend into your request from http://c.m.163.com)
        pathRewrite: {
          '^/api': ' ' // Because there is no/API in the real path, it is necessary to remove this paragraph to concatenate the correct address forwarding request}}}}Copy the code

The code requested by Axios

axios({
    url: '/api/nc/article/headline/T1348647853363/0-40.html'
})
Copy the code

Production environment

Solution: use Node + Express to build a local server to start CORS and start your front-end request and address to deploy the server online

You start cORS on the server that you start cORS on and it’s the proxy server that makes the request and the proxy server forwards the request to the actual interface server and there’s no cross-domain problem between the servers and cross-domain is the security mechanism of the browser