1. 程式人生 > >解決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

隨著前端框架的發展,如今前後端資料分離已經成了趨勢,也就是說,前端只需要用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>
至此,問題已經解決: