programing

레일 4 앱에서 CORS를 활성화하는 방법

procenter 2023. 9. 7. 23:58
반응형

레일 4 앱에서 CORS를 활성화하는 방법

지금 막 머리를 뽑으려고 하는데...아침부터 이 레일즈 앱에서 CORS를 활성화하려고 했는데 작동이 안 됩니다.는 랙 코르스 젬을 사용해서 이것시도했지만 이 답변과 게시물은 모두 성공하지 못했습니다.

누가 제게 올바른 방향을 가르쳐 주실 수 있나요?

여기 내 js가 있습니다.

      var req = new XMLHttpRequest();

      if ('withCredentials' in req) {
            // req.open('GET', "https://api.github.com/users/mralexgray/repos", true);
            req.open('GET', "http://www.postcoder.lc/postcodes/" + value, true);
            // Just like regular ol' XHR
            req.onreadystatechange = function() {
                if (req.readyState === 4) {
                    if (req.status >= 200 && req.status < 400) {
                        // JSON.parse(req.responseText) etc.
                        console.log(req.responseText);
                    } else {
                        // Handle error case
                    }
                }
            };
            req.send();
        }

(외부 클라이언트에서) 이 url(https://api.github.com/users/mralexgray/repos 을 시도해보면 문제가 Rails API에 있다고 가정합니다.내가 틀렸나요?

편집: 현재 컨트롤러에 이 내용이 있습니다.

skip_before_filter :verify_authenticity_token
before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers

# For all responses in this controller, return the CORS access control headers.
def cors_set_access_control_headers
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
  headers['Access-Control-Max-Age'] = "1728000"
end

# If this is a preflight OPTIONS request, then short-circuit the
# request, return only the necessary headers and return an empty
# text/plain.

def cors_preflight_check
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
  headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version'
  headers['Access-Control-Max-Age'] = '1728000'
end

코르스를 사용해야 합니다.

사용하기 좋은 DSL을 제공합니다.config/application.rb, 복잡한 헤더 작업 대신 그리고 필터 전에.

매우 관대한 것은 다음과 같습니다만, 물론 약간의 맞춤이 필요할 것입니다.

use Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: :any
  end  
end

::Cors는 원산지 간 리소스 공유를 지원합니다.

랙코를 활성화하는 단계:

  1. 보석을 젬 파일에 추가합니다.

    주옥같은 돌팔매

  2. 아래 코드를 config/application.rb에 추가합니다.

레일 3/4를 사용하는 경우:

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', :headers => :any, :methods => :any
  end
end

레일 5를 사용하는 경우:

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: :any
  end
end

제게 도움이 된 것은 다음과 같습니다.

  1. Gemfile에 추가:gem 'rack-cors'그리고나서bundle install

  2. 새 파일 만들기/config/initializers/cors.rb

  3. 파일 안에 다음을 넣습니다.

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

그거에요!

참고로 설명은 여기서 직접 왔습니다.

언급URL : https://stackoverflow.com/questions/29751115/how-to-enable-cors-in-rails-4-app

반응형