Ajax cross-Domain Request interface Introduction and solution

Source: Internet
Author: User
Tags cmss

In the front-end development process, will often appear in front-end code and background services are not a server situation, when the front-end JS code calls the background interface, there will be cross-domain issues. :

1. The domain is identified by the header of the URL. The browser does not attempt to determine if the same IP address corresponds to two domains or whether two domains are on the same IP. The head of the URL refers to Window.location.protocol +window.location.host, which can also be understood as "Domains, protocols and ports must match".

2, because of the cross-domain problems caused by protocol, IP, port, it is useless to modify the front-end code only.

Below we mainly describe the front end and the background server is not the same domain name, caused by cross-domain issues. If the front-end JS cross-domain access to the background interface, the browser console will error.

Can be resolved in two ways: Jsonp and cors.

First,JSONP

Jsonp can implement cross-domain access for GET requests.

Front-End Code:

$.ajax ({    type: "Get",    URL: "http://localhost:8080/bcse-oa/login?userName=admin&password=123",    DataType: "Jsonp",//The data type is JSONP      jsonp: "Jsonpcallback",//the server is used to receive the callback call of the function name of the parameter      success:function ( Data) {        //callback function    },    error:function () {    

Abbreviated form, the effect is the same

$.getjson ("http://localhost:8080/bcse-oa/login?userName=admin&password=123&jsonpCallback=?",     function (data) {    //callback});    

Background Java code:


PrintWriter out = Response.getwriter (); Jsonobject Resultjson = jsonobject.fromobject (map); Assemble  the json String jsonpcallback = request.getparameter ("Jsonpcallback") as needed;//client request parameter  out.println ( Jsonpcallback+ "(" +resultjson.tostring () + ")");//return JSONP format data     

Second, CORS

Cors defines a mechanism for cross-domain access that enables AJAX to be accessed across domains. CORS allows a network application on one domain to submit cross-domain AJAX requests to another domain.

Compared with JSONP, Cors is undoubtedly more advanced, convenient and reliable.

1. JSONP can only implement get requests, and Cors supports all types of HTTP requests.

2, using cors, developers can use ordinary XMLHttpRequest to initiate requests and obtain data, than JSONP have better error handling.

3. JSONP is primarily supported by older browsers, which often do not support cors, and most modern browsers already support Cors.

With cors, you need to differentiate between simple requests and preflight mechanisms.

In the Cors specification, the three http, and post are simple HTTP Methods, Accept, Accept-language, Content-language, and header content-type for multipart/ One of the Form-data, application/x-www-form-urlencoded, and Text/plain is called a "simple request Header".

Simple request: The request takes a simple HTTP method, the custom request header is empty or the custom request header is a simple request header. Because requests with these attributes are not intended to update (add, modify, and delete) resources, the processing of requests by the server does not result in a change in its own maintenance resources. If it is a simple request, set Access-control-allow-origin to request a site IP or *.

preflight mechanism : The browser sends a pre-check request (preflight requests) before sending a real cross-domain resource request. The preflight request is a request that takes the Http-options method, which is a request that does not contain a principal, and the header associated with the user credential is also rejected. Some of the secondary authorization information based on a real resource request is included in the corresponding header of this preflight request.

After receiving a preflight request, the resource's provider determines whether the requesting site is trustworthy, whether the request takes the HTTP method and the custom header is allowed, based on the relevant header it provides for authorization validation. If the preflight request does not pass authorization verification, the resource provider typically returns a response with a status of "Reuqest". If passed, a response with a status of "OK" is returned, and the authorization information is included in the response header. In addition to the "Access-control-allow-origin" header described above, the response of the preflight request also has the following 3 typical headers.

Access-control-allow-methods: Cross-domain resource request allows a list of HTTP methods to be used.

Access-control-allow-headers: A list of custom headers that are allowed to be carried by cross-domain resource requests.

Access-control-max-age: The time, in seconds, that the browser can cache response results, which allows the browser to avoid frequent sending of preflight requests.

After the browser receives the preflight response, it determines whether the actual cross-domain resource request for subsequent sends is accepted, based on the response header, with the following test logic:

The source site represented by the requested "Origin" header must exist in the list of sites identified by the "Access-control-allow-origin" response header.

The response header "Access-control-allow-methods" does not exist, or the "Access-control-request-method" header of the preflight request represents the request method within its list.

The header name of the "Access-control-request-headers" header store for the preflight request is within the list of headers that are represented by the response header "Access-control-allow-headers".

The browser sends a true cross-domain resource request only if it is determined that the server is bound to accept it. The results of the preflight response will be cached by the browser, and the cached results will be verified by the browser user during the time set in the "Access-control-max-age" header, so no preflight requests will be sent during this period.

In the Cors specification, the server uses the response header "Access-control-allow-credentials" to indicate whether it supports user credentials. The types of user credentials here include cookies, http-authentication headers, and client-side certificates (Tls/ssl with client-side certificates). If "Access-control-allow-credentials" is set to true, then "Access-control-allow-origin" cannot be "*" and must be the specified site.

Background code settings with pre-check mechanism:

Response.setheader ("Access-control-allow-origin", "*"); Response.setheader ("Access-control-allow-methods", "POST, GET, OPTIONS, DELETE "), Response.setheader (" Access-control-max-age "," 3600 "); Response.setheader (" Access-control-allow-headers "," X-requested-with,content-type ");


You can create a filter

Package Com.chinamobile.cmss.bcse.web.interceptor;import Java.io.ioexception;import Javax.servlet.filter;import Javax.servlet.filterchain;import Javax.servlet.filterconfig;import Javax.servlet.servletexception;import Javax.servlet.servletrequest;import Javax.servlet.servletresponse;import Javax.servlet.http.HttpServletResponse; Import org.springframework.stereotype.Component; @Componentpublic class Simplecorsfilter implements Filter {public void DoFilter (ServletRequest req, servletresponse Res, Filterchain chain) throws IOException, servletexception {httpse    Rvletresponse response = (httpservletresponse) res;    Response.setheader ("Access-control-allow-origin", "*");    Response.setheader ("Access-control-allow-methods", "POST, GET, OPTIONS, DELETE");   Response.setheader ("Access-control-max-age", "3600");    Response.setheader ("Access-control-allow-headers", "X-requested-with,content-type");  Chain.dofilter (req, res); } public void init (Filterconfig filterconfig) {} public void deStroy () {}} 


Add code to Web. XML:

<filter>    <filter-name>cors</filter-name>     <filter-class> com.chinamobile.cmss.bcse.web.interceptor.simplecorsfilter</filter-class></filter>< filter-mapping>    <filter-name>cors</filter-name>    <url-pattern>/*</url-pattern > </filter-mapping>


You can also modify Web. XML only. Add maven dependencies in the MAVEN framework

<dependency>    <groupId>com.thetransactioncompany</groupId>    <artifactId> Cors-filter</artifactid>    <version>2.5</version></dependency>


Web. XML JOIN Configuration

<filter> <filter-name>CORS</filter-name> <filter-class> Com.thetransactioncompany.cors.corsfilter</filter-class> <init-param> <param-name>cors.allowor        igin</param-name> <param-value>*</param-value> </init-param> <init-param> <param-name>cors.supportedMethods</param-name> <param-value>get, POST, HEAD, PUT, delete,option </param-value> </init-param> <init-param> <param-name>cors.supportedheaders</param -name> <param-value>accept, Origin, X-requested-with, Content-type, Last-modified</param-value> & lt;/init-param> <init-param> <param-name>cors.exposedHeaders</param-name> <param- value>set-cookie</param-value> </init-param> <init-param> <param-name>cors.support Scredentials</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>cors.maxAge</param-name> <param-value>3600</param-value> </init-param></filter><filter-mapping> <fil Ter-name>cors</filter-name> <url-pattern>/*</url-pattern></filter-mapping>


Ajax cross-Domain Request interface Introduction and solution

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: info-contact@alibabacloud.com 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.