Je suis en train de créer une API simple à l'aide de rails-api gem et pour le frontend j'utilise AngularJS. Lorsque j'envoie une requête get au serveur rails du navigateur, il donne la réponse JSON appropriée (par exemple http://localhost:3000/tasks) mais quand j'essaie d'accéder à la même chose d'angulaire en utilisant $ http.get (http://localhost:3000/tasks) il va à la place à la fonction de gestionnaire d'échec de la réussite. Que dois-je faire?impossible d'accéder aux données à partir des rails api dans angularjs
Voici mon code
Tâches contrôleur
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
Code angulaire
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>
Lorsque je visite la page HTML il montre erreur en alerte
Merci pour votre aide. Cela a fonctionné parfaitement. –