gpt4 book ai didi

javascript - 在 Rails 服务器上允许跨域访问

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:31:34 25 4
gpt4 key购买 nike

我在 Angular 中有一个前端 Web 应用程序,在 Rails 中有一个后端。从前端我有 javascript 代码发出 POST http 请求:

$scope.onSave = function () {
$http.post('http://localhost:3000/documents', { user: $scope.user, formData: $scope.formData }, function (response) {
$scope.isSaved = true;
console.log(response);
if (response.success) {
console.log("It has been successfully saved!")
}
});
}

在提交按钮上,我调用了上面的函数:

<button type="submit" class="btn btn-success" ng-click="onSave()">Submit</button>

然后我得到一个错误提示

XMLHttpRequest cannot load http://localhost:3000/documents. 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:3001' is therefore not allowed access. The response had HTTP status code 404.

我知道我需要允许跨域访问,但我不确定如何在 Rails 服务器端实现这一点。

最佳答案

  1. 添加this gem "rack-cors" 到你的 Gemfile。

  2. 将此添加到您的 config/application.rb 文件中。

   config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: [:get, :post, :patch, :delete, :put, :options]
end
end

关于javascript - 在 Rails 服务器上允许跨域访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36683686/

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