You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic移动端PUT请求跨域报错:缺少Access-Control-Allow-Origin头

Fixing CORS Preflight Error for PUT Requests in Ionic + Rails 5.2 API

Hey there, let’s tackle that frustrating CORS preflight error you’re hitting with your Ionic app and Rails API. Non-GET/POST methods like PUT trigger an automatic browser preflight OPTIONS request, and it looks like your Rails server isn’t properly set up to allow that from your Ionic origin. Here’s how to fix it step by step:

1. Install and Set Up the Rack-CORS Gem

First, make sure your Rails API has the tooling to handle cross-origin requests:

  • Open your Gemfile and add this line (if it’s not already there):
    gem 'rack-cors'
    
  • Run bundle install to install the gem.

2. Configure CORS Rules

Create or edit the file config/initializers/cors.rb (if the file doesn’t exist, just create it) with this configuration:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    # List your Ionic app's origins here—include both dev and production URLs
    origins 'http://localhost:8100', 'your-production-ionic-domain.com'
    
    resource '*',
      headers: :any,
      # Critical: Include OPTIONS to handle preflight requests
      methods: [:get, :post, :put, :patch, :delete, :options, :head],
      # Uncomment this if your requests send credentials (like auth tokens in cookies)
      credentials: true
  end
end

Quick Tips:

  • Don’t use a wildcard * for origins if your app sends credentials—browsers block this for security. Always list specific domains.
  • The OPTIONS method is non-negotiable here—it’s what the browser uses to "check" if the PUT request is allowed.

3. Restart Your Rails Server

This is easy to overlook! Any changes to initializer files require a server restart to take effect:

  • For local development: Stop and restart your Rails server.
  • For your Heroku-deployed API: Push your updated code to Heroku, or run heroku restart if you’ve already deployed the changes.

4. Verify the Fix

Test if the CORS headers are working with a simple curl command:

curl -X OPTIONS -H "Origin: http://localhost:8100" https://votingapi.herokuapp.com/api/v1/something -I

Check the response headers—you should see Access-Control-Allow-Origin: http://localhost:8100 listed. If you do, the configuration is working correctly.

5. Quick Ionic Side Check

Double-check your PUT request in Ionic:

  • Make sure you’re not sending custom headers that aren’t explicitly allowed (if you are, either add them to the headers list in your CORS config or use headers: :any).
  • Confirm your request uses a valid content type (like application/json)—while this rarely causes preflight issues, it’s good to rule out.

内容的提问来源于stack exchange,提问作者Holger Tidemand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:34:36