拒绝从'URL'执行脚本,因为它的MIME类型('application / json')不可执行,并且启用了严格的MIME类型检查

时间:2014-09-04 05:14:05

标签: ruby-on-rails cors mime-types

我知道这个问题已被多次询问,但在我的情况下。 Firefox正在运行,但chrome给了我这个错误:

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.

我有一个wordpress网站,我将向REST服务器发送REST调用(jsonp请求)。我在下面对RAILS中的CORS进行了更改

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_url值为http://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中它给了我错误。

2 个答案:

答案 0 :(得分: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

现在,上述更改适用于所有浏览器。

答案 1 :(得分:0)

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

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

这对我有用。