Refused to execute script from '*' because its MIME type ('application/json') is not executable, and strict MIME type checking is enabled

后端 未结 1 381
旧巷少年郎
旧巷少年郎 2021-01-05 05:04

I am a newbie to AngularJS. I am using a rails application to expose data in json format. The data is to be used by angular app. The angular repo and the rails repo are comp

相关标签:
1条回答
  • 2021-01-05 05:41

    Hey so I believe your problem is that your rails controller is returning JSON and NOT JSONP. Your controller has to explicitly specify a callback function, which can be specified by the request params.

    See Handling jsonp in rails 3 controller for an example of returning JSONP from a rails controller

    So your rails code would look like (argh my rails is very very rusty...):

    class Api::V1::PhonesController < ApplicationController
      def index
        if params[:callback]
          format.js { render :json => {:phones => Phone.all.to_json}, :callback => params[:callback] }
        else
          format.json { render json: {:phones => Phone.all.to_json}}
        end
    end
    

    Then for the angular side, this answer should help you out: parsing JSONP $http.jsonp() response in angular.js

    And I think your angular would then look like:

    var appServices = angular.module('appServices', []);
    
    phoneCatApp.factory('appServices', ['$http', '$q', function($http, $q){
      var url = "http://localhost:3000/api/v1/";
    
      //get all phones
      this.getPhones = function(){
        var defered = $q.defer();
        var listApi = url + "phones?callback=JSON_CALLBACK";
    
        $http.jsonp(listApi).then(function(results){
          defered.resolve(results);
        }, function(error){
          defered.reject(error);
        });
        return defered.promise;
        }
      return this;
    }]);
    
    0 讨论(0)
提交回复
热议问题