No 'Access-Control-Allow-Origin' header is present on the requested resource. 'Ajax cross-domain access solution (reproduced)

Solemnly declare: This article is reproduced from the blog of zhoucheng05_13

No 'Access-Control-Allow-Origin' header is present on the requested resource.

当使用ajax访问远程服务器时,请求失败,浏览器报如上错误。这是出于安全的考虑,默认禁止跨域访问导致的。

1. What is cross-domain access

For example : in A website, we want to use Ajax to get specific content in B website. If website A and website B are not in the same domain, then there is a cross-domain access problem. You can understand that two domain names cannot send requests or request data across domain names, otherwise it is insecure. Cross-origin access violates the same-origin policy. For details of the same-origin policy, you can click the following link: Same-origin_policy
In a word, the same-origin policy stipulates that the browser's ajax can only access the same origin (same domain name or IP) as its HTML page. )resource of.

2. Solutions

There are two commonly used solutions, which can be divided into client-side solutions and server-side solutions. Let's start with the server-side solution:

    • Server-side solution 
      Add "Access-Control-Allow-Origin" to the filter or servlet on the server side to 
      response.setHeader("Access-Control-Allow-Origin", "*"); 
      allow cross-domain access, and "*" to allow cross-domain access from all sources, which can also be replaced with a specific domain name or ip. 
      Obviously, this method cannot be done by non-site owners. And this method is vulnerable to CSRF attacks.

客户端解决方案:
copy code
 1 $(function($){
 2       var url = 'http://*****/index';
 3       $.ajax(url, {
 4         data: {
 5           'cityname': '成都',
 6           'date': '2016.12.12'
 7         },
 8         dataType: 'jsonp',
 9         crossDomain: true,
10         success: function(data) {
11           if(data && data.resultcode == '200'){
12             console.log(data.result.today);
13           }
14         }
15       });
copy code

Set the dataType attribute in the ajax request to "jsonp", jsonp was born specifically to solve cross-domain access.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324890361&siteId=291194637