This article will introduce the cross-domain scenarios that xiaobian has encountered in his work and the solutions.

Scenario 1: Cross-domain synchronization between the front and back ends during development

Solutions:

  1. Use Webpack to solve cross-domain problems

  2. Use Nginx to resolve cross-domains

  3. Cross-domain resolution using CORS

Scenario 2: The front and back ends are deployed in different domains

Solutions:

  1. Use Nginx to resolve cross-domains

  2. Cross-domain resolution using CORS

The solution

First let’s prepare a simple project for demonstration.

Project preparation steps:

  1. Create a folder cross-domain.

  2. Go to the cross-domain folder and create a Web folder (for storing front-end code) and a Server folder (for storing back-end code).

  3. Prepare front-end projects.

Go to the Web folder, create the index.html file, and create the index.js file.

Index.html reads as follows:

<! DOCTYPEhtml>
<html lang="zh">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Cross-domain demo</title>
    </head>
    <body>Cross-domain demo<button id="btn">Click on me to make an Ajax request</button>
        <h1 id="main"></h1>
        <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.3.1/jquery.min.js"></script>
        <script src="./index.js"></script>
    </body>
</html>
Copy the code

Index.js contains the following contents:

$(function() {$('#btn').on('click'.function() {
        $.ajax({
            // url: 'http://localhost:9527/getData', / / if direct access to the interface can produce cross domain, An error (Access to the XMLHttpRequest at 'http://localhost:9527/getData' from origin 'http://0.0.0.0:8080' has had been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.)
            url: '/api/getData'.// '/ API 'cross-agent identity, configured in webpack.config.js
            success: function(res) {$('#main').text(res.data)
            }
        });
    });
});
Copy the code
  1. Prepare back-end projects.

Go to the server folder and create the app.js file.

The contents of app.js are as follows:

const express = require('express')
const app = express()
const port = 9527
/ / interface address to http://localhost:9527/getData
app.get('/getData'.(req, res) = > {
    let tmpData = {
        code: 200.msg: 'success'.data: 'This is background data! '
    }
  res.send(tmpData)
})

const server = app.listen(port, () = > {
  console.log(`Example app listening at http://localhost:${port}`)})Copy the code

Open the command line in the Server folder.

  • Run yarn init -y to initialize the project. (NPM or CNPM can be used if you do not want to use yarn.)

  • Run the yarn add [email protected] command to install express

  • Run the node app.js command to start the back-end service

Get a get method interface at http://localhost:9527/getData

If directly under http://0.0.0.0:8080/ service request http://localhost:9527/getData interface can produce cross-domain request is not successful. What is cross-domain

The project directory structure is:

├── ├─ web ├─ index.html ├─ ├─ server ├─Copy the code

The project address

Use Webpack to solve cross-domain problems

Addressing cross-domains using Webpack is suitable for cross-domain mediation of front and back ends during development.

Open the command line in the Web folder.

Open the package.json file and add the following code before devDependencies:

"scripts": {
    "serve": "webpack-dev-server"
},
Copy the code

Go to the Web folder and create the webpack.config.js file. The contents of webpack.config.js are as follows:

module.exports = {
    entry: './index.js'.devServer: {
        port: 8080.host: '0.0.0.0'.open: true.inline: true.hot: true.disableHostCheck: true.proxy: {
            '/api': {
                target: 'http://localhost:9527'.// Service address
                ws: false.changeOrigin: true.pathRewrite: { '^/api': ' ' }
            }
        }
    }
}
Copy the code

Execute commands on the command line yarn serve to start the development service, will open the browser address as http://0.0.0.0:8080/ page, click the button to send the request, see http://localhost:8080/api/getData interface request is successful, Through the agent after it actually get the http://localhost:9527/getData interface of data.

Note: Webpack development environment to handle cross-domain, packaged to be deployed to the production environment of the code is static files, is not resolved cross-domain, some students will think that in the development environment with Webpack to handle cross-domain, production environment will also be handled.

Use Nginx to resolve cross-domains

  1. Install nginx

MAC environment installation tutorial

Windows environment installation tutorial

After nginx is installed, modify the nginx.conf file in the conf folder as follows:

user root owner; worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 8080; server_name localhost; # root D:/cross-domain/web; Nginx: root /Users/its-wild/cross-domain/web: root /Users/its-wild/ web: root /Users/its-wild/ web # MAC environment index index.html index.htm; } # proxy_pass http://localhost:9527;} # proxy_pass http://localhost:9527; After # port without /, actual access address for http://localhost:9527/api/getData proxy_pass http://localhost:9527/; / # port after the belt, the actual access address to http://localhost:9527/getData proxy_redirect off; Proxy_set_header Host 127.0.0.1; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Cookie $http_cookie; allow all; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } include servers/*; }Copy the code

Here is the nginx.conf file in the MAC environment.

After startup nginx, http://localhost:8080/, click on the button to send the request, see http://localhost:8080/api/getData interface request is successful, Through the agent after it actually get the http://localhost:9527/getData interface of data.

Tip: Front-end development is packaged with static files. Deploying nGINx on a server is the same as starting service development with Nginx in a development environment.

Cross-domain resolution using CORS

Cross-origin Resource Sharing (CORS) is the most recommended cross-domain Resource Sharing solution. Not only does it work with all methods, but it’s also much more convenient and simple. Only modern browsers support it, of course.

Details about CORS

This thing only needs the background to do processing, the front end directly access the interface full path, if you need special processing can refer to the CORS detailed documentation.

Here we modify the contents of app.js as follows:

const express = require('express')
const app = express()
const port = 9527


// Set cross-domain access
app.all(The '*'.function (req, res, next) {
    res.header("Access-Control-Allow-Origin"."*");
    res.header("Access-Control-Allow-Headers"."X-Requested-With");
    res.header("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By".'3.2.1')
    res.header("Content-Type"."application/json; charset=utf-8");
    next();

})

/ / interface address to http://localhost:9527/getData
app.get('/getData'.(req, res) = > {
    let tmpData = {
        code: 200.msg: 'success'.data: 'This is background data! '
    }
    res.send(tmpData)
})

const server = app.listen(port, () = > {
    console.log(`Example app listening at http://localhost:${port}`)})Copy the code

Modify index.js as follows:

$(function() {$('#btn').on('click'.function() {
        $.ajax({
            url: 'http://localhost:9527/getData'.// URL: '/ API /getData', // '/ API 'cross-agent identity, configured in webpack.config.js
            success: function(res) {$('#main').text(res.data)
            }
        });
    });
});
Copy the code

Restart the back-end service, and then start a front-end service through HTTP-server (open the command line in the Web folder, execute http-server -p 8080-O), and click the button on the http://127.0.0.1:8080/ page to initiate a request. Will see in the network request address for http://localhost:9527/getData request returns success.

Tip: 127.0.0.1, 0.0.0.0, localhost, and local IP (e.g. 10.0.123.57) all point to the same address