What is across the field

Any difference between the protocol, domain name, or port of the requested URL and the protocol, domain name, or port of the current page URL is cross-domain. For security reasons, browsers’ common source policies restrict cross-domain access. To learn about the browser’s source policy, see here.

How to resolve cross-domain

  1. For local development, the proxy target and changeOrigoin are set in webpack-dev-server
  2. jsonp, using script tags that are not bound by homology. The specific approach is:
    1. Specify method names, such as CB, on the front and back ends.
    2. The front end defines the CB method.
    3. The script tag requests the URL
    4. The back end returns a directly executed method to the front end, and since the front end made the request with the script tag, the returned method is executed immediately, putting the data to be returned in the method parameters
window.cb = function(res){
    console.log(res)
}
<script src="http://www.aaa.com/login?userName=admin&callback=cb"></script>

// Back end returns
ctx.body = `${query.cb}(The ${JSON.stringify({status: 'success', type: 1}}))) `

Copy the code
  1. CORS, CORS is a W3C standard, full name is “cross-origin Resource Sharing” (Cross-domain resource Sharing). For details on CORS, please see here. Set access-Control-allow-origin to * to accept requests from any domain name. CORS requests do not send cookies and HTTP authentication information by default. To send cookies to the server, specify the access-Control-allow-credentials field with the server’s permission.

  2. Nginx, Nginx is a lightweight Web/reverse proxy server and email (IMAP/POP3) proxy server.

/ / Nginx configurationServer {# listening in9999Port to listen9999;
    # 域名是localhost
    server_name localhost;
    #凡是localhost:9999/ API like this, all forward to the real server address HTTP://localhost:9998 
    location ^~ /api {
        proxy_pass http://localhost:9998;}}Copy the code