Front-and-back interaction to resolve Cross-domain request issues _ cross-domain request

Source: Internet
Author: User

The separation and development of the front and back ends often involve the separation and development of the front and rear ends.

However, JS prohibits cross-domain requests. For example, Ajax requests in api.test.com such as access to aaa.test.com servers

Then the front and rear end have to take some measures to solve

Back-End (Java):

Set the response header in the Interceptor or filter, take the interceptor in SPRINGMVC for example:

Package cn.creat.zhxy.interceptor;


Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;


Import Org.springframework.web.servlet.HandlerInterceptor;
Import Org.springframework.web.servlet.ModelAndView;

public class Alloworigininterceptor implements handlerinterceptor{


@Override
public void Aftercompletion (HttpServletRequest request,
HttpServletResponse Res, Object arg2, Exception arg3)
Throws Exception {

}


@Override
public void Posthandle (HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, Modelandview arg3) throws Exception {
}


@Override
public boolean prehandle (HttpServletRequest request, HttpServletResponse Res,
Object arg2) throws Exception {
Res.setheader ("Access-control-allow-origin", Request.getheader ("Origin"));
Res.setheader ("Access-control-allow-methods", "POST, Get, OPTIONS, DELETE");
Res.setheader ("Access-control-max-age", "0");
Res.setheader ("Access-control-allow-headers", "Origin, No-cache, X-requested-with, If-modified-since, Pragma, Last-modified, Cache-control, Expires, Content-type, X-e4m-with,userid,token ");
Res.setheader ("Access-control-allow-credentials", "true");
Res.setheader ("xdomainrequestallowed", "1");
return true;
}


}

Front End section:

(function () {
$.ajax ({
Add these lines of code
Xhrfields: {
Withcredentials:true
},
Crossdomain:true,

});

This solves the Cross-domain problem

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.