跨域的常見問題和解決方案

第一種

No 'Access-Control-Allow-Origin' header is present on the requested resource
The response had HTTP status code 404

出現這種狀況的緣由以下:html

  • 本次ajax請求是「非簡單請求」,因此請求前會發送一次預檢請求(OPTIONS)
  • 服務器端後臺接口沒有容許OPTIONS請求,致使沒法找到對應接口地址

解決方法前端

//node
//koa
const Koa = require('koa');
const app = new Koa();
const router = require('./router');

app.use(router.routes());
app.use(router.allowedMethods());

//java 
//CorsFilter.java
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest)servletRequest; 
       
        String method = request.getMethod();
        if(method.equalsIgnoreCase("OPTIONS")){ //處理OPTIONS請求
            servletResponse.getOutputStream().write("Success".getBytes("utf-8"));
        }else{
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
 
    @Override
    public void destroy() {
 
    }
}
//web.xml
<filter>
    <filter-name>corsFilter</filter-name>
    <filter-class>xxx.xxx.CorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>corsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

第二種

No 'Access-Control-Allow-Origin' header is present on the requested resource
The response had HTTP status code 405java

緣由是接口不容許 會或者缺乏GET,POST對應的接口暴露,好比 GET寫成了POST,或者是其餘安全策略阻止了訪問node

第三種

No 'Access-Control-Allow-Origin' header is present on the requested resource
status 200webpack

緣由是 頭部匹配時出現不匹配現象
解決方法nginx

//node
async (ctx, next) => {
    ctx.set({
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
        'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
    });
    ctx.type = 'application/json'
    ctx.body = {code:0}
}

//nginx
server {
    listen       80;
    server_name  www.chuchur.com;
    location / {
        proxy_pass   http://www.chuchur.org;  #反向代理
        index  index.html index.htm;

        # 當用webpack-dev-server等中間件代理接口訪問nignx時,此時無瀏覽器參與,故沒有同源限制,下面的跨域配置可不啓用
        add_header Access-Control-Allow-Origin http://www.chuchur.com;  #當前端只跨域不帶cookie時,可爲*
        add_header Access-Control-Allow-Credentials true;
    }
}
//java 在Filter 裏面加入

String origin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", 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,Authorization");
response.setHeader("Access-Control-Allow-Credentials", "true");

第四種

Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.
緣由是客戶端頭部信息('x-csrf-token')不被後端接收.兩邊同步下就能夠了web

第五種

The 'Access-Control-Allow-Origin' header contains multiple values ', ', but only one is allowed.ajax

出現這個緣由是 重複配置了跨域的頭部信息致使的, 好比:json

//node http://192.168.0.100:7001 node run in 7001
async (ctx, next) => {
    ctx.set({
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
        'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
    });
    ctx.type = 'application/json'
    ctx.body = {code:0}
}

//nginx proxy to nginx 7001
server {
    listen       80;
    server_name  www.chuchur.com;
    location / {
        proxy_pass       http://192.168.0.100:7001; //轉發到node的7001
        add_header Access-Control-Allow-Origin *;  //當前端只跨域不帶cookie時,可爲*
        add_header Access-Control-Allow-Credentials true;
    }
}
//

當客戶端經過nginx 上傳圖片的時候就會出現這個問題, node 和 nginx 同時配置了跨域的頭部信息後端

相關文章
相關標籤/搜索