【发布时间】:2017-10-29 00:44:12
【问题描述】:
所以我尝试使用 Content-Type: application/json 从 Angular 向我的 Rails 后端发送 POST 请求。我在控制台中收到以下错误:
angular.js:12578 选项http://localhost:3000/api/student_create 404(未找到)
和
XMLHttpRequest 无法加载 http://localhost:3000/api/student_create。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:8008' 不允许访问。响应的 HTTP 状态代码为 404。
请注意,当我使用Content-Type: application/x-www-form-urlencoded 时,post 请求可以正常工作
它也可以在 Postman 中使用,在 header 中设置 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
【问题讨论】:
-
您要发布的数据的大小是多少?
-
只是文字。 (角度控制器中的
data对象) -
你能验证你发送的对象是一个有效的json对象吗
-
@alphapilgrim 是的,它是有效的,它只是
data对象 -
Rails 代码需要一个路由来响应使用 CORS 标头的 OPTIONS 请求。
标签: javascript ruby-on-rails angularjs json cors