JavaScript跨域請求RESTful Web Service

來源:互聯網
上載者:User

當我們用js請求RESTful Web Service的時候,通常會出現跨域無法訪問的問題,也就是無法正常得到我們要的值。jsonp是個解決問題的方法。但是,我們希望訪問RESTful Web Service就像一般的ajax方法一樣,不用每個都去搞一個jsonp和callback。這就需要我們在服務端進行一些設定,下面我用一個簡單的 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;public class SimpleCORSFilter implements Filter {    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");        response.setHeader("Access-Control-Max-Age", "3600");        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");        chain.doFilter(req, res);    }    public void init(FilterConfig filterConfig) {}    public void destroy() {}}   
  • Access-Control-Allow-Origin 為允許哪些Origin發起跨域請求. 這裡設定為"*"表示允許所有,通常設定為所有並不安全,最好指定一下。
  • Access-Control-Allow-Methods 為允許請求的方法.
  • Access-Control-Max-Age 表明在多少秒內,不需要再發送預檢驗請求,可以緩衝該結果
  • Access-Control-Allow-Headers 表明它允許跨域請求包含content-type頭,這裡設定的x-requested-with ,表示ajax請求


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.