首页 文章

无法使用content-type进行POST:application / json from angular to rails

提问于
浏览
0

所以我试图用Content-Type发送一个POST请求:application / json从angular到我的rails后端 . 我在控制台中收到以下错误:

angular.js:12578选项http:// localhost:3000 / api / student_create 404(未找到)

XMLHttpRequest无法加载http:// localhost:3000 / api / student_create . 对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头 . 因此不允许来源'http:// localhost:8008'访问 . 响应具有HTTP状态代码404 .

请注意,当我使用 Content-Type: application/x-www-form-urlencoded 时,帖子请求正常工作

它也适用于Postman,并在 Headers 中设置了application / json Content-Type .

角度控制器:

.controller('View1Ctrl', function($scope, $http) {

  var data = {
    name: "name"
  };
  $http({
    url: 'http://localhost:3000/api/student_create',
    dataType: 'json',
    method: 'POST',
    data:data,
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*"
    }
  }).then(function(response) {
    console.log(response)
  }, function(error) {
    console.log(error)
  });

});

API控制器(Rails):

class ApiController < ApplicationController
     before_action :set_headers
     skip_before_action :verify_authenticity_token

  def set_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    end
  def create_student
    student = StudentUser.new
    student.name= params[:name]
    student.save
    render json: "test".to_json #temporary
  end

路线: post 'api/student_create' => 'api#create_student'

编辑:前端在http://localhost:8008上,后端在localhost:3000上

2 回答

  • 1

    嗨,当我与Angular交互Rails时,我也遇到了这个问题 . 经过大量的研究,我发现宝石'rack-cors'解决了这个问题 . 您可以按照其文档here . 默认情况下,Rails不允许跨源资源共享 . 所以基本上它很好地处理交叉原始请求 .

    脚步:

    安装gem:

    gem install rack-cors
    

    或者在你的Gemfile中:

    gem 'rack-cors', :require => 'rack/cors'
    

    application.rb文件

    module YourApp
      class Application < Rails::Application
    
        # ...
    
        # Rails 3/4
    
        config.middleware.insert_before 0, "Rack::Cors" do
          allow do
            origins '*'
            resource '*', :headers => :any, :methods => [:get, :post, :options]
          end
        end
    
        # Rails 5
    
        config.middleware.insert_before 0, Rack::Cors do
          allow do
            origins '*'
            resource '*', :headers => :any, :methods => [:get, :post, :options]
          end
        end
    
      end
    end
    
  • 0

    How to Configure CORS Accept Headers in Rails API Application尝试以下内容

    因此,即使您的消费者使用“localhost:3000”并且您的提供者位于“localhost:3001”,除非您的Web服务设置了允许的CORS策略,否则响应将被忽略 . 此策略由提供者在HTTP响应中设置特定的CORS头,其定义为强制执行的消费者应用(例如,浏览器) . 例如,配置这些标头:

    # in config / application.rb
    config.action_dispatch.default_headers = {
      'Access-Control-Allow-Origin' => 'http://my-web-service-consumer-site.com',
      'Access-Control-Request-Method' => % w {
        GET POST OPTIONS
      }.join(",")
    }
    

    每个站点:

    Please note, that setting 'Access-Control-Allow-Origin' => '*' is highly discouraged, unless you are providing a public API that is intended to be accessed by any consumer out there.

相关问题