欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot解決ajax跨域問題的方法

 更新時間:2018年03月06日 14:21:42   作者:幕三少  
這篇文章主要為大家詳細(xì)介紹了SpringBoot解決ajax跨域問題的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下

SpringBoot解決ajax跨域,供大家參考,具體內(nèi)容如下

一、第一種方式

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:第一種存在一個問題,當(dāng)服務(wù)器拋出 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>獲取其他內(nèi)容</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' 務(wù)必加上你請求時所帶的header。例如本例中的“Token”,其實(shí)是前端傳給后端過來的。如果記不得也沒有關(guān)系,瀏覽器的調(diào)試器會有詳細(xì)說明。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 深入剖析構(gòu)建JSON字符串的三種方式(推薦)

    深入剖析構(gòu)建JSON字符串的三種方式(推薦)

    下面小編就為大家?guī)硪黄钊肫饰鰳?gòu)建JSON字符串的三種方式(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • 解決idea報錯 Connot resolve column 的問題

    解決idea報錯 Connot resolve column 的問題

    這篇文章主要介紹了解決idea報錯 Connot resolve column 的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • IDEA中Maven依賴包下載不了的問題解決方案匯總

    IDEA中Maven依賴包下載不了的問題解決方案匯總

    這篇文章主要介紹了IDEA中Maven依賴包下載不了的問題解決方案匯總,文中通過圖文示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Spring Cloud Stream微服務(wù)消息框架原理及實(shí)例解析

    Spring Cloud Stream微服務(wù)消息框架原理及實(shí)例解析

    這篇文章主要介紹了Spring Cloud Stream微服務(wù)消息框架原理及實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-06-06
  • Android入門簡單實(shí)例

    Android入門簡單實(shí)例

    這篇文章主要介紹了Android入門簡單實(shí)例,對于初學(xué)Android的朋友有一定的借鑒價值,需要的朋友可以參考下
    2014-08-08
  • Java如何實(shí)現(xiàn)Unicode和中文相互轉(zhuǎn)換

    Java如何實(shí)現(xiàn)Unicode和中文相互轉(zhuǎn)換

    這篇文章主要介紹了Java如何實(shí)現(xiàn)Unicode和中文相互轉(zhuǎn)換問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • MyEclipse去除網(wǎng)上復(fù)制下來的代碼帶有的行號(正則去除行號)

    MyEclipse去除網(wǎng)上復(fù)制下來的代碼帶有的行號(正則去除行號)

    這篇文章主要介紹了MyEclipse去除網(wǎng)上復(fù)制下來的代碼帶有的行號(正則去除行號)的相關(guān)資料,需要的朋友可以參考下
    2017-10-10
  • SpringBoot整合Redis使用RedisTemplate和StringRedisTemplate

    SpringBoot整合Redis使用RedisTemplate和StringRedisTemplate

    Spring?Boot?Data(數(shù)據(jù))?Redis?中提供了RedisTemplate和StringRedisTemplate,其中StringRedisTemplate是RedisTemplate的子類,兩個方法基本一致。本文介紹了SpringBoot整合Redis使用RedisTemplate和StringRedisTemplate的方法,需要的可以參考一下
    2022-12-12
  • 詳解Java設(shè)計模式之外觀模式

    詳解Java設(shè)計模式之外觀模式

    在Java開發(fā)中,設(shè)計模式是一種十分常見的編程思想,它可以幫助我們解決很多實(shí)際開發(fā)中的問題,本篇文章將介紹一種常見的設(shè)計模式——外觀模式,并結(jié)合實(shí)際的開發(fā)場景進(jìn)行講解,需要的朋友可以參考下
    2023-06-06
  • SpringBoot使用Kaptcha實(shí)現(xiàn)驗(yàn)證碼的生成與驗(yàn)證功能

    SpringBoot使用Kaptcha實(shí)現(xiàn)驗(yàn)證碼的生成與驗(yàn)證功能

    這篇文章主要介紹了SpringBoot使用Kaptcha實(shí)現(xiàn)驗(yàn)證碼的生成與驗(yàn)證功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-03-03

最新評論