0

I am trying to create a simple todo api using rails-api gem and for frontend I am using AngularJS. When I send a get request to rails server from browser its giving the appropriate JSON response (e.g. http://localhost:3000/tasks) but when I try to access the same from angular using $http.get(http://localhost:3000/tasks) it is going to the failure handler function instead of success. What shall I do?

Here is my code

Tasks Controller

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 code

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>

When I visit the HTML page it shows error as alert

1 Answer 1

1

It sounds like a CORS problem. Does your web service support CORS? If not, you can use tools like rack cors.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.