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

Rails 7 API结合React前端遭遇跨域请求拦截问题求助

Rails + React 跨域请求问题解决方案

跨域错误提示

问题说明

在Rails项目中集成React前端后,尝试向https://localhost:3000/search发送请求时出现跨域错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:300/search

按常规CORS配置方案修改后问题仍未解决。

涉及代码

PortfolioContainer.jsx(注:原文件后缀标注错误,应为React组件文件)

import React, { Component } from 'react'
import Search from "./Search";
import Calculate from "./Calculate";
import axios from 'axios'

class PortfolioContainer extends Component {
constructor(props) {
    super(props)

    this.state = {
        name: '',
        portfolio: [],
        search_results: [],
        active_currency: null,
        amount: ''
    }

    this.handleChange = this.handleChange.bind(this)
}

handleChange(e) {
    // this.setState({
    //     [e.target.name]: e.target.value
    // })

    axios.post('https://localhost:300/search', {
        search: e.target.value
    })
        .then((data) => {
            debugger
        })
        .catch((data) => {
            debugger
        })
}

render() {
    return (
        <div>
            <Search handleChange={this.handleChange} />
            <Calculate />
        </div>

    )
    }
}

export default PortfolioContainer

config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
    allow do
      origins '*'

      resource '*',
        headers: :any,
        methods: [:get, :post, :put, :patch, :delete, :options, :head]
    end
  end

解决步骤

  1. 修正请求URL错误
    错误提示里的请求地址是https://localhost:300/search,比正确的Rails默认端口3000少了一个0——这是核心问题之一,请求根本没发到后端服务上。把axios请求的URL改成:

    axios.post('https://localhost:3000/search', {
        search: e.target.value
    })
    
  2. 确保CORS配置生效

    • 确认已安装rack-cors gem:在Gemfile中添加gem 'rack-cors',执行bundle install。
    • 修改cors.rb后必须重启Rails服务器,否则配置不会加载。
    • 查看Rails服务器日志,检查OPTIONS预检请求是否被正常处理。如果日志里看不到OPTIONS请求,说明请求还没到后端,优先排查URL、端口和网络问题。
  3. 统一前后端协议
    如果React前端运行在HTTP环境(比如http://localhost:3001),而后端用了HTTPS,跨域规则会更严格。要么统一用HTTP/HTTPS,要么在cors配置中明确允许对应来源。

  4. 开发环境快捷方案
    开发阶段可以直接在React项目的package.json中添加代理,绕开CORS配置:

    "proxy": "http://localhost:3000"
    

    之后axios请求可以简化为:

    axios.post('/search', {
        search: e.target.value
    })
    

    这种方式无需配置CORS,适合快速开发测试。

内容的提问来源于stack exchange,提问作者Benjamin Sunderland

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 09:05:33