溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Springboot怎么實現(xiàn)跨域訪問無需使用jsonp的代碼

發(fā)布時間:2021-05-21 10:29:30 來源:億速云 閱讀:218 作者:小新 欄目:編程語言

小編給大家分享一下Springboot怎么實現(xiàn)跨域訪問無需使用jsonp的代碼,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

Springboot 實現(xiàn)跨域訪問 無需使用jsonp

在springboot的攔截器中添加respone的頭信息即可

@Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    //String origin = (String) request.getRemoteHost()+":"+request.getRemotePort();
    response.addHeader("Access-Control-Allow-Origin", "*");
    //System.out.println("Access-Control-Allow-Origin");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    //System.out.println("Access-Control-Allow-Methods");
    response.addHeader("Access-Control-Max-Age", "3600");
    //System.out.println("Access-Control-Max-Age");
    response.addHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
    //System.out.println("Access-Control-Allow-Headers");
    response.addHeader("Access-Control-Allow-Credentials","true");
    //System.out.println("Access-Control-Allow-Credentials");
    String api_key = request.getParameter("api_key");
    String api_secret = request.getParameter("api_secret");
;
      if (check(api_key,api_secret)){
        return true;
      }
      response.sendError(400,"api_key or api_secret are error");
      return false;
  }
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
  @Bean
  APIIntercepter apiIntercepter() {
    return new APIIntercepter();
  }
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    // 添加一個攔截器,連接以/v1為前綴的 url路徑
    registry.addInterceptor(loginIntercepter()).addPathPatterns("/admin/**");
    registry.addInterceptor(apiIntercepter()).addPathPatterns("/v1/**");
  }
}

springboot是什么

springboot一種全新的編程規(guī)范,其設(shè)計目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程,SpringBoot也是一個服務(wù)于框架的框架,服務(wù)范圍是簡化配置文件。

看完了這篇文章,相信你對“Springboot怎么實現(xiàn)跨域訪問無需使用jsonp的代碼”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI