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页面它显示错误作为警报
谢谢你的帮助。它工作完美。 –