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

标签 javascript ruby-on-rails angularjs server request

我在 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/

相关文章:

javascript - 在使用后重新分配变量?

ruby-on-rails - 使用 strftime 解析日期

javascript - 自定义 ngInclude : variable in template not replaced

javascript - 到目前为止以给定格式解析字符串

javascript - transcrypt 中的可迭代仿真

ruby-on-rails - 部署到 heroku 的 Ruby on Rails 应用程序显示 "We' 抱歉,但出了点问题”

ruby-on-rails - 这是通过 Controller 进行质量分配的安全方法吗?

angularjs Material 设计嵌套列表

javascript - 为 Angular JS 启用 html 5 模式会抛出 JS 错误 : Failed to instantiate module due to: TypeError: Cannot read property 'html5Mode' of undefined

javascript - 使用 meteor 模板助手获取 DOM 元素