简体   繁体   English

无法从angularjs中的Rails API访问数据

[英]unable to access data from rails api in angularjs

I am trying to create a simple todo api using rails-api gem and for frontend I am using AngularJS. 我正在尝试使用rails-api gem创建一个简单的todo api,对于前端,我正在使用AngularJS。 When I send a get request to rails server from browser its giving the appropriate JSON response (eg 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. 当我从浏览器向Rails服务器发送get请求时,它会给出适当的JSON响应(例如http:// localhost:3000 / tasks ),但是当我尝试使用$ http.get( http:// localhost :3000 / tasks),它将转到失败处理函数而不是成功。 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 的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 当我访问HTML页面时,它显示错误为警报

It sounds like a CORS problem. 听起来像是CORS问题。 Does your web service support CORS? 您的Web服务是否支持CORS? If not, you can use tools like rack cors . 如果没有,您可以使用诸如机架cors之类的工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM