Ionic移动端PUT请求跨域报错:缺少Access-Control-Allow-Origin头
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
Gemfileand add this line (if it’s not already there):gem 'rack-cors' - Run
bundle installto 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 restartif 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
headerslist in your CORS config or useheaders: :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

