nginx 實現 ajax 跨域請求Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin


AJAX從一個域請求另一個域會有跨域的問題。那么如何在nginx上實現ajax跨域請求呢?

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

要在nginx上啟用跨域請求,需要添加add_header Access-Control*指令。如下所示:

location / {
        add_header         'Access-Control-Allow-Origin' 'https://api.xxxx.com'; 
      add_header      'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header         "Access-Control-Allow-Credentials" "true";
        add_header         "Access-Control-Allow-Headers" "x-requested-with,content-type";
        proxy_pass         http://localhost:8080;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
}

如果需要允許來自任何域的訪問,可以這樣配置:

 add_header         'Access-Control-Allow-Origin' '*'; 

主要是添加了三個用於控制CORS的頭信息:

  • Access-Control-Allow-Origin:允許的來源
  • Access-Control-Allow-Credentials:設置為true,允許ajax異步請求帶cookie信息
  • Access-Control-Allow-Headers:設置為x-requested-with,content-type,允許ajax余部請求。
  • Access-Control-Allow-Methods GET, POST, OPTIONS :設置指定請求的方法,可以是GET,POST等;

這個配置也可以在spring mvc里配置。

問題:

配置好后,異步跨域請求成功。

當發起post請求,請求的數據是放在request body里,請求的Content-Type為application/json。Spring MVC需要使用@RequestBody來接收數據。

這是一次非簡單的請求,瀏覽器會發起一次Options的預請求。發起Options請求報403錯誤:

Failed to load https://api.xxxx.com/auth.json: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://other.xxxx.com’ is therefore not allowed access. The response had HTTP status code 403.

解決方法

原以為是自己的配置有誤,但找了很多資料可以確定配置是沒有問題。后來debug跟蹤Spring MVC DispatcherServlet的調用,發現在DispacerServlet是因為沒有找都到執行Options請求的方法。

在做跨域請求時,配置好CORS相關頭信息后,以為就可以了,這很容易忽略在Spring MVC添加對Options請求的處理。

解決方法有兩種:

  • 在攔截器統一添加對Options請求的支持
  • 添加一個支持Options的ReqeuestMapping。

攔截器示例:

public class CrosDomainAllowInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        if(request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            response.setStatus(HttpStatus.OK.value());
            return false;
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
    }
}

@RequestMapping示例

@RequestMapping(value = "/*",method = RequestMethod.OPTIONS)
public ResponseEntity handleOptions(){
    return ResponseEntity.noContent();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



猜您在找 跨域請求錯誤: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' heade Vue前台,跨域請求報錯“Response to preflight request doesn't pass access control check” 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:8000' is therefore not allowed a 接口在dev環境報跨域問題(has been blocked by CORS policy:Response to preflight request doesn't pass access control check:No 'Access-Control-Allow-Origin' header ispresent on the requested resource.),qa環境正常 has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource Response to preflight request doesn't pass access control check: It does not 跨域報錯has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request. ajax post上傳數據時,前端出現的跨域權限問題:ccess to XMLHttpRequest at ‘’rom origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok st
 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM