2016-05-13 7 views
0

rails-api gemを使用して単純なtodo apiを作成しようとしています。フロントエンドにAngularJSを使用しています。適切なJSONレスポンス(例:http://localhost:3000/tasks)をブラウザから取得すると、railsサーバにリクエストを送信するときに、$ http.get(http://localhost:3000/tasks))を使用して同じ角度にアクセスしようとすると、代わりにエラーハンドラ関数が実行されます成功の。私は何をするもの?ここ angularjsのrails apiからデータにアクセスできない

がある私のコード

タスクコントローラ

class TasksController < ApplicationController 
    before_action :set_task, only: [:show, :update, :destroy] 

    # GET /tasks 
    # GET /tasks.json 
    def index 
    @tasks = Task.all 

    render json: @tasks 
    end 

    # GET /tasks/1 
    # GET /tasks/1.json 
    def show 
    render json: @task 
    end 

    # POST /tasks 
    # POST /tasks.json 
    def create 
    @task = Task.new(task_params) 

    if @task.save 
     render json: @task, status: :created, location: @task 
    else 
     render json: @task.errors, status: :unprocessable_entity 
    end 
    end 

    # PATCH/PUT /tasks/1 
    # PATCH/PUT /tasks/1.json 
    def update 
    @task = Task.find(params[:id]) 

    if @task.update(task_params) 
     head :no_content 
    else 
     render json: @task.errors, status: :unprocessable_entity 
    end 
    end 

    # DELETE /tasks/1 
    # DELETE /tasks/1.json 
    def destroy 
    @task.destroy 

    head :no_content 
    end 

    private 

    def set_task 
     @task = Task.find(params[:id]) 
    end 

    def task_params 
     params.require(:task).permit(:title, :completed, :order) 
    end 
end 

角度コード

angular 
.module('app', []) 
.controller('MainCtrl', [ 
'$scope', 
'$http', 
function($scope,$http){ 
    $scope.test = 'Hello world!'; 

    $http.get('http://localhost:3000/tasks').then(function(response){ 
    $scope.tasks = response.data; 
    },function(response){ 
    alert('error'); 
    }) 
}]); 

HTML

<body ng-app="app" ng-controller="MainCtrl"> 
    <div> 
     {{test}} 
    </div> 
    <ul> 
     <li ng-repeat="task in tasks">{{task.title}}</li> 
    </ul> 
</body> 

私はHTMLページにアクセスすると、それはエラーとして警告

答えて

1

それはCORS問題のように聞こえる示しています。あなたのWebサービスはCORSをサポートしていますか?そうでない場合は、rack corsのようなツールを使用できます。

+0

ありがとうございました。それは完璧に働いた。 –

関連する問題