Front-end solution to cross-domain interfaces

Produced by cross-domain reasons: limited browser's same-origin policy, it does not allow sharing of resources under different domain names, different ports, different protocols.

Cross-domain solution:

(1) jsonp

Usually in order to reduce the load on the web server, we have to separate js, css, img and other static resources to another independent domain name server, and then load the static resources from a different domain in html pages by the respective labels are browser allow, based on this principle, we can create a dynamic script by, and then request a URL with parameters to achieve cross-domain communication.

Shortcoming applies only way to get request method, and only supports cross-domain HTTP request, there are some limitations on the request, but it is the first to solve the problem of cross-domain. jquery in to use this method to solve the problem of cross-domain:

$("#demo").click(function(){
    $.ajax({
        url : 'http://www.demo.cn/Test/crossDomain',
        data : {},
        type : 'get',
        dataType : 'jsonp',  
        success : function (res) {
            conosle.log(res);
        }
    });
});

(2) CORS request, just browsing support and servers, almost all browsers support this feature.

CORS entire communication, the browser is done automatically, for developers to communicate with the homologous cors ajax no difference. Once the browser ajax cross-domain request will automatically add some additional request header, sometimes a pre-request, and then sending a request by the preflight data transmission seat. This method requires the rear end of the head to modify the response:

 header(Access-control-Allow-Origin:  * ');   
//*代表允许访问的来源(所有),但是你在请求头携带cookie等东西时,必须要指明,也就是设置跨域白名单。

header('Access-control-Allow-Method: POST,GET');  //允许访问的方式

Ordinary cross-domain requests: only the server settings Access-Control-Allow-Origin can be, no need to set the front end, with a cookie request to: the front and rear ends need to be set.

Primeval ajax:

// 前端设置是否带cookie
xhr.withCredentials = true;

jquery ajax:

$.ajax({
    ...
   xhrFields: {
       withCredentials: true    // 前端设置是否带cookie
   },
    ...
});

(3) set the proxy. It can be simply understood when client sends a request, not directly to the server, but the first to the intermediate layer agent; Similarly, when the server returns the data to the first agent of the intermediate layer.

Webpack configuration API to develop agents to solve cross-domain as an example:

① need to use locally developed plug-ins: webpack-dev-server.

② configure http-proxy, configured in webpack configuration file (webpack.config.js) in

module.exports = {
 ...
 // webpack-dev-server的配置
 devServer: {
     proxy: {
        // 当请求是以/api开头的接口,则帮代理访问到http://localhost
        '/api/*': {
             target: 'http://localhost', //要代理的域名,必须要加上http
            //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,
            这样客户端端和服务端进行数据的交互就不会有跨域问题
             changeOrigin: true,
             pathRewrite:{
               '^/api':'/'  // 替换target地址,也就是说以后请求http://localhost/demo1地址时,
                            axios请求地址直接写成/api/demo1
         }
     }
 },
 ...
};

In the dev environment, because the configuration of the proxyTable can achieve cross-domain. But in a production environment, api prefix is ​​written directly to die, resulting in an error. It can be set dynamically by determining the development environment or a production environment, if the production environment has baseUrl = '', the development environment baseUrl = '/ api'.

axios.defaults.baseURL = (process.env.NODE_ENV===‘development’)?'/api':''

 

 

 

 

 

Published 24 original articles · won praise 3 · views 20000 +

Guess you like

Origin blog.csdn.net/sunny123x/article/details/105137712