gpt4 book ai didi

javascript - 无法使用内容类型 : application/json from angular to rails 进行 POST

转载 作者:行者123 更新时间:2023-12-03 04:13:43 25 4
gpt4 key购买 nike

因此,我尝试从 Angular 向我的 Rails 后端发送内容类型为 application/json 的 POST 请求。我在控制台中收到以下错误:

angular.js:12578 OPTIONS http://localhost:3000/api/student_create 404 (Not Found)

XMLHttpRequest cannot load http://localhost:3000/api/student_create. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8008' is therefore not allowed access. The response had HTTP status code 404.

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

它也可以在 Postman 中使用,并在 header 中设置 application/json Content-Type。

Angular Controller :

.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 Controller (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

最佳答案

嗨,当我与 Angular 交互 Rails 时,我也遇到了这个问题。经过大量研究后,我发现 gem“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

关于javascript - 无法使用内容类型 : application/json from angular to rails 进行 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44230087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com