$http.post 在 Rails 路由中变为 [OPTIONS]
Posted
技术标签:
【中文标题】$http.post 在 Rails 路由中变为 [OPTIONS]【英文标题】:$http.post becomes [OPTIONS] in Rails route 【发布时间】:2015-11-11 01:57:57 【问题描述】:这是我的 Angular 文件:
registrationModule.config(['$httpProvider', function($httpProvider)
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
]);
registrationModule.controller("registrationController",function($scope,$http)
$http.get("http://localhost:3000/logins/workspace_list?token=tempore").
success(function(response)
$scope.workspaces=response;
);
$scope.register=function()
var postData=$scope.module_entry;
if(postData.password==postData.repassword)
$http.post('http://localhost:3000/users',postData);
else
alert("Password not correctly verified");
);
我把它放在我的 Rails 应用程序控制器中(我是 API 新手,所以我在拼凑我在 Google 搜索中找到的信息)
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
headers['Access-Control-Max-Age'] = "1728000"
end
def cors_preflight_check
if request.method == 'OPTIONS'
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'Content-Type,X-Requested-With, X-Prototype-Version, Token'
headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
end
最后这是我在用户控制器中放置的:
class UsersController < ApplicationController
def index
end
def show
@user=User.where('username=? and password=?',params[:username],params[:password])
unless(!@user) do
return @user
end
render nothing, :status=>400
end
def create
unless(!authenticate()) then
@user=User.new
@user.username=@registration.username
@user.password=@registration.password
@user.token=(0...8).map (65 + rand(26)).chr .join
@user.workspace=Workspace.find(@registration.workspace)
@user.save
render json: @user
end
render :html, :status=>400
end
def authenticate
@registration=JSON.parse params[:module_entry]
@logged_workspace=@registration.workspace
@logged_token=@registration.token
@verify=Workspace.where('id=? and token=?',@logged_workspace,@logged_token)
unless @verify then
return true
end
return false
end
结束
这以“路由 [OPTIONS] 没有匹配项”/users 结束。我读到这是一个 CORS 问题,我已经尝试了所有建议,但最终还是这样。我哪里错了?
【问题讨论】:
【参考方案1】:我正在使用这个 gem https://github.com/cyu/rack-cors 对我来说很好用
【讨论】:
以上是关于$http.post 在 Rails 路由中变为 [OPTIONS]的主要内容,如果未能解决你的问题,请参考以下文章
AngularJS - 带有 Rails 3.2.3 的 $http POST
mvccontrib 测试助手和验证 http post 路由和参数