无法访问 rails api 中的数据 angularjs

unable to access data from rails api in angularjs

我正在尝试使用 rails-api gem 创建一个简单的待办事项 api 并且对于前端我正在使用 AngularJS。当我从浏览器向 rails 服务器发送获取请求时,它会给出适当的 JSON 响应(例如 http://localhost:3000/tasks) but when I try to access the same from angular using $http.get(http://localhost:3000/tasks) 它将转到失败处理函数而不是成功。什么我该怎么做?

这是我的代码

任务控制器

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代码

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 页面时,它显示 error 为 alert

听起来像是 CORS 问题。您的 Web 服务是否支持 CORS?如果没有,您可以使用 rack cors.

等工具