簡體   English   中英

無法從angularjs中的Rails API訪問數據

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

我正在嘗試使用rails-api gem創建一個簡單的todo api,對於前端,我正在使用AngularJS。 當我從瀏覽器向Rails服務器發送get請求時,它會給出適當的JSON響應(例如http:// localhost:3000 / tasks ),但是當我嘗試使用$ 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
.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頁面時,它顯示錯誤為警報

聽起來像是CORS問題。 您的Web服務是否支持CORS? 如果沒有,您可以使用諸如機架cors之類的工具。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM