2016-05-13 44 views
0

我正在嘗試使用rails-api gem創建簡單的待辦事項api,並且我正在使用AngularJS創建前端。當我從瀏覽器向瀏覽器發送get請求時,它會給出相應的JSON響應(例如http://localhost:3000/tasks),但是當我嘗試使用$ 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

謝謝你的幫助。它工作完美。 –