欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot解决ajax跨域问题的方法

程序员文章站 2022-06-21 16:07:10
springboot解决ajax跨域,供大家参考,具体内容如下 一、第一种方式 1、编写一个支持跨域请求的 configuration import org....

springboot解决ajax跨域,供大家参考,具体内容如下

一、第一种方式

1、编写一个支持跨域请求的 configuration

import org.springframework.context.annotation.configuration;
import org.springframework.web.servlet.config.annotation.corsregistry;
import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter;

/**
 * 处理ajax请求跨域的问题
 * @author levin
 * @time 2017-07-13
 */
@configuration
public class corsconfig extends webmvcconfigureradapter {
  static final string origins[] = new string[] { "get", "post", "put", "delete" };
  @override
  public void addcorsmappings(corsregistry registry) {
    registry.addmapping("/**").allowedorigins("*").allowcredentials(true).allowedmethods(origins)
        .maxage(3600);
  }
}

2、http请求接口

@restcontroller
public class hellocontroller {

  @autowired
  helloservice helloservice;


  @getmapping(value = "/test", produces = mediatype.application_json_utf8_value)
  public string query() {
    return "hello";
  }
}

二、 第二种方式(推荐)

ps:第一种存在一个问题,当服务器抛出 500 的时候依旧存在跨域问题

@springbootapplication
@componentscan
@enablediscoveryclient
public class managementapplication {

  public static void main(string[] args) {
    springapplication.run(managementapplication.class, args);
  }

  private corsconfiguration buildconfig() {
    corsconfiguration corsconfiguration = new corsconfiguration();
    corsconfiguration.addallowedorigin("*");
    corsconfiguration.addallowedheader("*");
    corsconfiguration.addallowedmethod("*");
    corsconfiguration.addexposedheader(httpheaderconstant.x_total_count);
    return corsconfiguration;
  }

  /**
   * 跨域过滤器
   *
   * @return
   */
  @bean
  public corsfilter corsfilter() {
    urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource();
    source.registercorsconfiguration("/**", buildconfig()); // 4
    return new corsfilter(source);
  }
}

2、index.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>跨域请求</title>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.ajax({url:"http://localhost:8080/test",success:function(result){
      $("#p1").html(result);
    }});
  });
});
</script>
</head>
<body>

<p width="500px" height="100px" id="p1"></p>
<button>获取其他内容</button>
</body>
</html>

三、第三种方式,编写filter过滤器

package com.cci.market.common.filter;

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;

/**
 * 处理跨域问题
 * @author mr.zheng
 * @date 2016/08/08
 *
 */
@component
public class originfilter implements filter {

  @override
  public void init(filterconfig filterconfig) throws servletexception {

  }

  @override
  public void dofilter(servletrequest req, servletresponse res,
      filterchain chain) throws ioexception, servletexception {
    httpservletresponse response = (httpservletresponse) res;
    response.setheader("access-control-allow-origin", "*");
    response.setheader("access-control-allow-methods", "post, get, options, delete,put");
    response.setheader("access-control-max-age", "3600");
    response.setheader("access-control-allow-headers", "x-requested-with");
    chain.dofilter(req, res);
  }

  @override
  public void destroy() {
    // todo auto-generated method stub

  }

}

四、nginx跨域配置

nginx跨域也比较简单,只需添加以下配置即可。

location / {
  proxy_pass http://localhost:8080;
  if ($request_method = 'options') {
    add_header 'access-control-allow-origin' '*';
    add_header 'access-control-allow-methods' 'get, post, options';
    add_header 'access-control-allow-headers' 'dnt,x-customheader,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,content-range,range,token';
    add_header 'access-control-max-age' 1728000;
    add_header 'content-type' 'text/plain; charset=utf-8';
    add_header 'content-length' 0;
    return 204;
  }
  if ($request_method = 'post') {
    add_header 'access-control-allow-origin' '*';
    add_header 'access-control-allow-methods' 'get, post, options';
    add_header 'access-control-allow-headers' 'dnt,x-customheader,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,content-range,range,token';
    add_header 'access-control-expose-headers' 'dnt,x-customheader,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,content-range,range,token';
  }
  if ($request_method = 'get') {
    add_header 'access-control-allow-origin' '*';
    add_header 'access-control-allow-methods' 'get, post, options';
    add_header 'access-control-allow-headers' 'dnt,x-customheader,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,content-range,range,token';
    add_header 'access-control-expose-headers' 'dnt,x-customheader,keep-alive,user-agent,x-requested-with,if-modified-since,cache-control,content-type,content-range,range,token';
  }
}

其中:add_header 'access-control-expose-headers' 务必加上你请求时所带的header。例如本例中的“token”,其实是前端传给后端过来的。如果记不得也没有关系,浏览器的调试器会有详细说明。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。