所以我试图用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 回答
嗨,当我与Angular交互Rails时,我也遇到了这个问题 . 经过大量的研究,我发现宝石'rack-cors'解决了这个问题 . 您可以按照其文档here . 默认情况下,Rails不允许跨源资源共享 . 所以基本上它很好地处理交叉原始请求 .
脚步:
安装gem:
或者在你的Gemfile中:
application.rb文件
从How to Configure CORS Accept Headers in Rails API Application尝试以下内容
每个站点:
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.