Home > Web Front-end > JS Tutorial > How to solve ajax cross-domain problem

How to solve ajax cross-domain problem

coldplay.xixi
Release: 2020-10-29 09:25:27
Original
2296 people have browsed it

Solution to ajax cross-domain problem: 1. Add Header to the response header to allow access; 2. jsonp only supports get requests but not post requests; 3. httpClient internal forwarding; 4. Use nginx to build an enterprise-level interface gateway Way.

How to solve ajax cross-domain problem

Related free learning recommendations: ajax (Video )

Solution to ajax cross-domain problem:

Solution 1: Add Header to the response header to allow access

Cross-Origin Resource Sharing (CORS) Cross-Origin Resource Sharing

The security foundation of this cross-domain access solution is based on "JavaScript cannot control this HTTP header"

It It is necessary to authorize whether to allow cross-domain access through the HTTP header returned by the target domain.

response.addHeader(‘Access-Control-Allow-Origin:*’);//允许所有来源访问 
response.addHeader(‘Access-Control-Allow-Method:POST,GET’);//允许访问的方式
Copy after login

Solution 2: jsonp only supports get requests but not post requests

Usage: ①Change dataType to jsonp ②jsonp: "jsonpCallback"— ——The actual value sent to the backend is http://a.a.com/a/FromServlet?userName=644064&jsonpCallback=jQueryxxx ③The backend obtains the jsonpCallback in the get request ④Construct the callback structure

$.ajax({
type : "GET",
async : false,
url : "http://a.a.com/a/FromServlet?userName=644064",
dataType : "jsonp",//数据类型为jsonp  
jsonp : "jsonpCallback",//服务端用于接收callback调用的function名的参数
success : function(data) {
alert(data["userName"]);
},
error : function() {
alert('fail');
}
});
 
//后端
        String jsonpCallback = request.getParameter("jsonpCallback");
//构造回调函数格式jsonpCallback(数据)
resp.getWriter().println(jsonpCallback+"("+jsonObject.toJSONString()+")");
Copy after login

JSONP implementation Principle

Under the same-origin policy, pages under a certain server cannot obtain data outside the server, that is, general ajax cannot make cross-domain requests. However, tags such as img, iframe, and script are exceptions. These tags can request data on other servers through the src attribute. Using the open policy of the

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template