前端:jquery ajax 跨域请求问题解决汇总

一般情况下跨域分两种请求方式:post、get;

1、post请求解决方式:

spring cloud 项目下:

后台demo:

@CrossOrigin(allowCredentials = "true", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.OPTIONS, RequestMethod.HEAD, RequestMethod.PUT, RequestMethod.PATCH}, origins = "*")
@RequestMapping(value = "/testPost", method = RequestMethod.POST)
    public int testPost(){
        LogHelper logHelper = new LogHelper();
        return SystemConstants.FW_SYS_SUCCESS;
    }

前端demo:

$.ajax({
        url:"http://192.168.xx.xx:xx/testPost",
        type:"POST",
        contentType:"text/json; charset=UTF-8",
        success:function(data){
        },error:function(){

        }
    });

以上为spring cloud项目下解决跨域较为方便的一种。

2、servlet配置文件方式,如下:

后台demo:

@RequestMapping(value = "/testPost", method = RequestMethod.POST)
public String testPost() {
    
    return "ok";
}

跨域拦截配置

<filter>
<filter-name>corsFilter</filter-name>
<filter-class>org.gateway.filter.CorsFilter</filter-class>
<init-param>
<param-name>allowOrigin</param-name>
<param-value>
http://192.168.100.67:8061,
http://cater.ypp2015.com,
</param-value>
</init-param>
<init-param>
<param-name>allowMethods</param-name>
<param-value>GET,POST,PUT,DELETE,OPTIONS</param-value>
</init-param>
<init-param>
<param-name>allowCredentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>allowHeaders</param-name>
<param-value>Origin,X-Requested-With,Content-Type,Accept</param-value>
</init-param>
</filter>

public class CorsFilter implements Filter {

private String allowOrigin;
private String allowMethods;
private String allowCredentials;
private String allowHeaders;
private String exposeHeaders;

@Override
public void init(FilterConfig filterConfig) throws ServletException {
allowOrigin = filterConfig.getInitParameter("allowOrigin");
allowMethods = filterConfig.getInitParameter("allowMethods");
allowCredentials = filterConfig.getInitParameter("allowCredentials");
allowHeaders = filterConfig.getInitParameter("allowHeaders");
exposeHeaders = filterConfig.getInitParameter("exposeHeaders");

}

@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (StringUtils.isNotEmpty(allowOrigin)) {
List<String> allowOriginList = Arrays.asList(allowOrigin.split(","));
if (CollectionUtils.isNotEmpty(allowOriginList)) {
String currentOrigin = request.getHeader("Origin");
if (allowOriginList.contains(currentOrigin)) {
response.setHeader("Access-Control-Allow-Origin", currentOrigin);
}
}
}
if (StringUtils.isNotEmpty(allowMethods)) {
response.setHeader("Access-Control-Allow-Methods", allowMethods);
}
if (StringUtils.isNotEmpty(allowCredentials)) {
response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
}
if (StringUtils.isNotEmpty(allowHeaders)) {
response.setHeader("Access-Control-Allow-Headers", allowHeaders);
}
if (StringUtils.isNotEmpty(exposeHeaders)) {
response.setHeader("Access-Control-Expose-Headers", exposeHeaders);
}
chain.doFilter(req, res);
}

@Override
public void destroy() {

}

3、get跨域

前端demo:

$.ajax({
        url:"http://192.168.xx.xx:xx/testGet",
        type:"get",

        datatype:"jsonp",

         jsonp:"callback",
         jsonpCallback:"successCallback",
        contentType:"text/json; charset=UTF-8",
        success:function(data){
        },error:function(){

        }
    });

后台方式:servlet

后台demo:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/json;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    String name = request.getParameter("name");
    String age = request.getParameter("age");
    try {
        
        String st = " 姓名:"+name+",age:"+age;
        System.out.println("------------");
        out.print("successCallback(" + st + ")");//尤其注意这里返回的数据格式: {"name":" jone:18865920808,age:30"}
        
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.flush();
        out.close();
    }

}

这里 在返回的时候会有:successCallback前缀格式:successCallback(Jsonobject.tostring()); 

4、springcloud 处理get跨域:(前端代码和上面3一样)

@CrossOrigin(allowCredentials = "true", allowedHeaders = "*",origins = "*",methods = {RequestMethod.GET})
@RequestMapping(value = "/testGet")
public String getCert() {
    return "ok";
}

 

上述是个人在 jquery ajax跨域问题上遇到的一点小坎,最后通过整理得到了get、post的两种处理方式,欢迎抛砖引玉;

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值