JavaScript calls RESTful API based on JSON across domains

  • 2021-07-02 23:11:09
  • OfStack

1. Basic terminology

AJAX (Asynchronous JavaScript And XML, Asynchronous JavaScript, and XML): AJAX is a technology for creating fast dynamic web pages, and AJAX enables web pages to be updated asynchronously by exchanging a small amount of data with the server in the background. This means that you can update parts of the page without reloading the entire page.

JSON (JavaScript Object Notation): JSON is a lightweight data interchange format, which can be regarded as multiple pairs of "key/value" wrapped in braces in the following format: {"firstName": "Brett", "lastName": "McLaughlin", "email": "abcdefg @ gmail. com"}.

Cross Domain (cross-domain): Cross-domain issues are caused by the homology policy in the JavaScript language security restrictions, and can occur on clients when using AJAX on a page to request access to data from other servers.

Same Origin Policy (Homologous Policy): Homologous policy means that a script can only read the attributes of windows and documents from the same source, and the domain name, protocol and port are the same, that is, homologous.

2. JavaScript cross-domain solution

At present, there are three main JavaScript cross-domain solutions:

Cross-domain based on iframe: Both pages must belong to a base domain (for example, both xxx. com, or xxx. com. cn), using the same 1 protocol (for example, both HTTP) and the same 1 port (for example, both 80). iframe scheme has too many restrictions on domain names, protocols and ports, so it is of little use.

Cross-domain based on Script tag (JSONP scheme): JSONP (JSON with Padding) is a "usage mode" of JSON, which is an unofficial cross-domain data exchange protocol and can be used to solve the problem of cross-domain data access of mainstream browsers. The limitation of the JSONP scheme is that JSONP can only fulfill GET requests.

Cross-domain (CORS scheme) based on background proxy: CORS (Cross-Origin Resource Sharing, cross-domain resource sharing) is an W3C standard, which allows browsers to send XMLHttpRequest requests to cross-source servers, thus overcoming the limitation that AJAX can only be used from the same source.

3. Cross-domain based on background agent (CORS scheme)

Specific solutions are as follows:

① Server side

The server side needs to add Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers and other fields to the normal HTTP response.

My server side is written in Python, and the HTTP request calls webob. Request.

The modification is to add the following lines after the line "res = req.get_response (self. app)":


res.headerlist.append(('Access-Control-Allow-Origin', '*')) 
res.headerlist.append(('Access-Control-Allow-Methods', 'GET, POST')) 
res.headerlist.append(('Access-Control-Max-Age', '3600')) 
res.headerlist.append(('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Max-Age, X-Auth-Token, Content-Type, Accept')) 

Among them, Access-Control-Allow-Origin is preferably limited to the front-end access address, which is relatively safe, such as:


res.headerlist.append(('Access-Control-Allow-Origin', 'http://10.111.121.26:8080')) 

In addition, Access-Control-Max-Age can set the cache time for CORS-related configurations so that clients do not have to make a pre-check request (Preflight Request) every time.

The preview request will first issue an OPTIONS method to the server with a request with an "Origin" header. Only after the request is allowed will a real cross-domain request be initiated.

Therefore, the server side also needs to let go of the pre-check request when authenticating X-Auth-Token, for example:


def process_request(self, req): 
if (req.headers.get('X-Auth-Token') != 'open-sesame') and (req.method != 'OPTIONS'): 
return exc.HTTPForbidden() 

② Client

HTTP requests need to be aware of several things:

data needs to be guaranteed to be a string in JSON format;

contentType specifies that the encoding format is UTF8;

dataType specifies that the returned content is in JSON format.

The specific calling code is as follows:


data_param = {"timeType":"LAST_7_DAYS", "hostType":"ALL_HOSTS"} 
$.ajax({ 
url:"http://172.16.17.11:41128/dpi/webApp/eventRetrieve", 
type: "POST", 
data:JSON.stringify(data_param), 
headers:{ 
"X-Auth-Token":"open-sesame", 
"Content-Type":"application/json" 
}, 
contentType: 'text/html; charset=UTF-8', 
dataType: "json", 
success: function(data) { 
alert(data); // Object 
}, 
error: function(XMLHttpRequest, textStatus, errorThrown) { 
alert(XMLHttpRequest.status); 
alert(XMLHttpRequest.readyState); 
alert(textStatus); 
}, 
complete: function(XMLHttpRequest, textStatus) { 
} 
}); 

Above is the site to introduce you JavaScript cross-domain call based on JSON RESTful API, I hope to help you, if you want to know more, please pay attention to this site website, thank you!


Related articles: