2014-09-04 198 views
0

我知道这个问题已被询问很多次,但在我的情况。 Firefox是工作,但Chrome是给我这个错误:拒绝从'URL'执行脚本,因为它的MIME类型('application/json')是不可执行的,并且启用严格的MIME类型检查

Refused to execute script from 'http://localhost:3000/get_all_test_centers?callback=undefined&_=1409807050144' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled.

我从那里我送一个REST调用轨服务器(JSONP请求)WordPress的网站。我下面的变化作出了CORS在Rails

mime_types.rb

Mime::Type.register 'application/json', :js

application_controller.rb

before_filter :set_access_control_headers 
def set_access_control_headers 
    headers['Access-Control-Allow-Origin'] = Rails.application.secrets.website_url 
    headers['Access-Control-Request-Method'] = 'GET, OPTIONS, HEAD' 
    headers['Access-Control-Allow-Headers'] = 'x-requested-with,Content-Type, Authorization' 
    end 

Rails.application.secrets.website_urlhttp://localhost/

控制研究呃输出:

def get_all_test_centers 
test_centers = TestCenter.all 
respond_to do |format| 
    format.js do 
    render :json => test_centers, :callback => 'renderTestCenters' 
    end 
end 
end 

我的WordPress JS:

var renderTestCenters = function(data) { 
    console.log(data); 
}; 

$.ajax({ 
    url: "http://localhost:3000/get_all_test_centers", 
    crossDomain: true, 
    type: "GET", 
    dataType: "JSONP", 
    jsonpCallback: renderTestCenters 
}); 

它工作正常,在Firefox,但在Chrome它给我的错误。

回答

1

所以最后我得到了答案。

更改您的ajax请求调用。

$.ajax({ 
    type: "GET", 
    url: "http://localhost:3000/get_all_test_centers", 
    crossDomain: true, 
    xhrFields: { 
     withCredentials: true 
    }, 
    success: function(data) { 
     console.log(data); 
    } 
}); 

Application_controller.rb

before_filter :cor 
def cor 
if request.headers["HTTP_ORIGIN"] 
    headers['Access-Control-Allow-Origin'] = Rails.application.secrets.website_url 
    headers['Access-Control-Expose-Headers'] = 'ETag' 
    headers['Access-Control-Allow-Methods'] = 'GET, POST, PATCH, PUT, DELETE, OPTIONS, HEAD' 
    headers['Access-Control-Allow-Headers'] = '*,x-requested-with,Content-Type,If-Modified-Since,If-None-Match,Auth-User-Token' 
    headers['Access-Control-Max-Age'] = '86400' 
    headers['Access-Control-Allow-Credentials'] = 'true' 
end 
end 

最后在我的控制器:

def get_all_test_centers 
test_centers = TestCenter.all 
respond_to do |format| 
    format.js do 
    render :json => test_centers 
    end 
end 
end 

现在上面的修改工作在所有浏览器。

0

有时结果不是由脚本直接处理的,所以为这些情况提供了:callback选项。

render json: test_centers, :callback => params[:callback]

这为我工作。

相关问题