First, what is cross-domain

When the protocol, domain name, or port of a URL request is different from the current page URL, it is called cross-domain.

Second, why cross-domain

The same origin policy is the core and most basic security function of the browser. Without the same origin policy, the browser is vulnerable to XSS and CSFR attacks.

3. Cross-domain solutions

1. JSONP

The principle of JSONP is to use script tag without cross-domain restriction. Through the SRC attribute of script tag, send GET request with callback parameter. The server will piece together the data returned by the interface into callback function and return it to the browser. The front-end retrieves the data returned by the callback function.Copy the code
<script>
    var script = document.createElement('script');
    script.type = 'text/javascript';

    // Pass the name of a callback function to the back end, so that the back end can execute the callback function defined in the front end when it returns
    script.src = 'http://localhost:3001/123? callback=handleCallback';
    document.head.appendChild(script);

    // The callback executes the function
    function handleCallback(res) {
        console.log(res);
    }
 </script>
Copy the code
var express= require('express'); var qs = require('querystring'); var app = express(); app.get('/123',function(req,res){ var params = qs.parse(req.url.split('? ') [1]); var fn = params.callback; Res.status (200) // jsonp returns setting res.write(fn + '(' + 1111 + ')'); res.end(); }); Var server = app.listen(3001, () => {console.log(' Start service! '); })Copy the code

The disadvantage is that only GET requests are supported

2. Cross-domain Resource Sharing (CORS)

CORS stands for Cross-Origin Resource Sharing. Access-control-allow-origin can be set only on the server. The front end does not need to be set. If cookie request is required, the front and back ends need to be set. // The front end sets whether to bring cookie xhr.withCredentials = true;

3. Nginx proxy is cross-domain

Access-control-allow-origin is a request header that can be set in a configuration file. And other fields.

Cross-domain problem: The same-origin policy is a security policy for browsers only. The server invokes the HTTP interface only using HTTP protocol, and does not need the same origin policy, so there is no cross-domain problem.Copy the code

4. The proxy agent

In the development environment, since the Vue rendering service and the interface proxy service are the same as Webpack-dev-server, there is no need to set headers cross-domain information between the page and proxy interface.

Module. exports = {dev: {proxy: {'/API ': {target: 'http://localhost:8080 ', pathRewrite: {'^/ API ': '}}}Copy the code