2014-09-04 196 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]

這爲我工作。

相關問題