Front end cross domain solutions

Time:2020-9-19

What is cross domain?

  • Cross domain is a restriction policy made by browser for security
  • Browser requests must follow the same origin policy: same domain name, same port and same protocol

How to solve cross domain problems?

There are three ways to solve cross domain problems

  • CORS cross domain
  • Jsonp cross domain
  • Agent cross domain
CORS cross domain:

CORS cross domain front-end does not need to be set, the back-end can directly add the previous code

The back-end is directly set to allow access to a domain name

header('Access-Control-Allow-Origin:https://segmentfault.com')

Or allow access to all domain names

header('Access-Control-Allow-Origin:*')
Jsonp cross domain:

Jsonp cross domain requires both front-end and back-end settings

front end:

Install the jsonp plug-in

npm i jsonp

Import the file that needs to be jsonp requested

<script>
import jsonp from 'jsonp'
export default {
  mounted() {
    let url = "http://localhost/zuoye/jsonp.php";
    jsonp(url,(err,res)=>{
      console.log(res);
    })
  }
};
</script>

Back end:

<?php
//The server returns JSON data  
$arr=array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);  
$result=json_encode($arr);  
//Dynamic execution of callback function  
$callback=$_GET['callback'];  
echo $callback."($result)"; 
?>

Then we can open the console and see the data.

Agent cross domain

The front end modifies the nginx server configuration, but the back end does not move.

For example, our local service is http://127.0.0.1.8080, and we want to request http: / / 127.0.0.1.9090/getdata interface

stay vue.config.js Inside:

module.exports = {
    devServer: {
        host: 'localhost',
        port: 8080,
        proxy: {
            '/api': {
                Target: "http: // 127.0.0.1.9090", <! -- requested interface -- >
                changeOrigin: true,
                pathRewrite: {
                    '/api': ''
                }
            }
        }
    }
}

On the requested page:


axios.get("api/getData")
      .then((data)=>{
        console.log(data);
      })

At this point, although the request is sent to: http://localhost : 8080 / API / GetData /, but it has been proxy to http: / / 127.0.0.1.9090/getdata /