我正在尝试使用rails-api gem创建一个简单的todo api,而对于前端我正在使用AngularJS。当我从浏览器向rails服务器发送get请求时,它会给出相应的JSON响应(例如http://localhost:3000/tasks),但是当我尝试使用 $ http.get({{3)从角度访问它时它会转到失败处理函数而不是成功。我该怎么办?
这是我的代码
任务控制器
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页面时,它会将错误显示为警告