JavaScript cross-origin calls of JSON-based RESTful APIs, jsonrestful

Source: Internet
Author: User

JavaScript cross-origin calls of JSON-based RESTful APIs, jsonrestful

1. Basic Terms

AJAX (Asynchronous JavaScript And XML, Asynchronous JavaScript And XML): AJAX is a technology used to create fast dynamic web pages. It performs a small amount of data exchange with the server in the background, AJAX enables asynchronous update of web pages. This means that you can update a part of a webpage without reloading the entire webpage.

JSON (JavaScript Object Notation): JSON is a lightweight data exchange format. It can be considered as multiple "key/value" pairs wrapped in braces. The format is as follows: {"firstName": "Brett", "lastName": "McLaughlin", "email": " "}.

Cross Domain (Cross-origin): Cross-origin is caused by the same-origin policy in the JavaScript language security restrictions. When AJAX requests are used to access data from other servers on the page, the client has a cross-origin problem.

Same Origin Policy (Same-Origin Policy): a Same-Origin Policy means that a script can only read the properties of windows and documents from the Same source. The domain name, protocol, and port are the Same, that is, the Same-Origin Policy.

2. JavaScript cross-origin Solution

Currently, there are three main JavaScript cross-origin solutions:

Cross-origin based on iframe: The two pages must belong to one basic domain (for example, or, use the same protocol (for example, HTTP) and the same port (for example, both 80 ). The iframe scheme imposes too many restrictions on domain names, protocols, and ports and is of little use.

Cross-origin based on Script tags (JSONP solution): JSONP (JSON with Padding) is a "usage mode" of JSON and an unofficial cross-Origin data interaction protocol, it can be used to solve cross-Origin data access problems of mainstream browsers. The JSONP solution has the following limitations: JSONP can only implement GET requests.

Cross-Origin (CORS) based on background Proxy: CORS (Cross-Origin Resource Sharing) is a W3C standard that allows browsers to send XMLHttpRequest requests to Cross-Origin servers, thus, AJAX can only be used in the same source.

3. Cross-origin based on background proxy (CORS solution)

The specific solution is as follows:

① Server side

The server must add Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, and other fields in the normal HTTP response.

My server is written in Python and webob. Request called by HTTP requests.

The modification method is to add the following lines after the line of code "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')) 

It is best to restrict Access-Control-Allow-Origin to the front-end Access address to ensure security. For example:

res.headerlist.append(('Access-Control-Allow-Origin', '')) 

In addition, Access-Control-Max-Age can set the cache time for CORS-related configurations, so that the client does not have to perform a precheck Request (Preflight Request) each time ).

The precheck request first sends an OPTIONS method to the server that contains the "Origin" header. A real cross-origin request is initiated only after the request is permitted.

Therefore, when the server authenticates X-Auth-Token, it must also pass the pre-check request, for example:

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

② Client

For HTTP requests, note the following:

Data must be a JSON string;

ContentType specifies that the encoding format is UTF8;

DataType specifies that the returned content is in JSON format.

The specific call code is as follows:

data_param = {"timeType":"LAST_7_DAYS", "hostType":"ALL_HOSTS"} $.ajax({ url:"", 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) { } }); 

The above is a full description of the JSON-based RESTful API for cross-origin JavaScript calling. I hope it will be helpful to you. If you want to learn more, please stay tuned to the help House website, thank you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.