首頁  >  文章  >  web前端  >  axios跨域請求出錯怎樣解決

axios跨域請求出錯怎樣解決

php中世界最好的语言
php中世界最好的语言原創
2018-03-23 14:15:292578瀏覽

這次帶給大家axios跨域請求出錯怎樣解決,axios跨域請求出錯怎樣解決的注意事項有哪些,下面就是實戰案例,一起來看一下。

錯誤訊息

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow- Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 403

隨著隨著 response had HTTP status code 403

隨著隨著前端框架的發展,如今前後端資料分離已經成了趨勢,也就是說,前端只需要用ajax請求後端的資料合成頁面,後端僅僅提供資料接口,給資料就行,好處就是前端程式設計師再也不用在自己的本地搭建Web伺服器,前端也不需要懂後端語法,後端也不需要懂前端語法,那麼簡化了開發配置,也降低了合作難度。

常規的GET,POST,PUT,DELETE請求是簡單請求(相對於OPTIONS請求),但是OPTIONS有點兒特別,它要先發送請求問問伺服器,你要不要我請求呀,要我就要發送資料過來咯(這完全是根據自己的理解寫的,如果有誤,敬請諒解,請參考阮一峰大神原文。)

在Vue的專案裡,Http服務採用Axios,而它正是採用OPTIONS請求。

如果僅僅在header裡面加入:

'Access-Control-Allow-Origin':*

,是並不能解決問題的,錯誤就是如文章開頭所示。

這兒就需要後台對OPTIONS請求額外處理。

本文以Spring MVC為例:

#新增一個攔截器類別:

public class ProcessInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
    httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    httpServletResponse.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    httpServletResponse.setHeader("X-Powered-By","Jetty");
    String method= httpServletRequest.getMethod();
    if (method.equals("OPTIONS")){
      httpServletResponse.setStatus(200);
      return false;
    }
    System.out.println(method);
    return true;
  }
  @Override
  public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
  }
  @Override
  public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  }
}

在spring-mvx.xml配置Spring 攔截器:

<mvc:interceptors> 
    <bean class="cn.tfzc.ssm.common.innterceptor.ProcessInterceptor"></bean> 
  </mvc:interceptors>
至此,問題已經解決:

##相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:
JS自動計算飯店住宿費用


圖片載入完畢前顯示載入圈的效果

######

以上是axios跨域請求出錯怎樣解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn