所以我试图用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,并在标题中设置了应用程序/ 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
答案 0 :(得分:1)
嗨,当我与Angular交互Rails时,我也遇到了这个问题。 经过大量的研究,我发现了宝石&#39; rack-cors&#39;这解决了这个问题。您可以按照其文档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
答案 1 :(得分: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(",")
}
每个网站:
请注意,该设置&#39; Access-Control-Allow-Origin&#39; =&GT; &#39; *&#39;非常不鼓励,除非您提供的公共API旨在供任何消费者访问。