登录 主页

rails 配置Access-Control-Allow-Origin 响应头部(浏览器console中报错:已拦截跨源请求:同源策略禁止读取位于 http://xxx/api/all_article 的远程资源(原因:CORS 头缺少 'Access-Control-Allow-Origin')状态码:200)

2023-10-28 07:59PM

我在 React 中引用接口:http://localhost:8888/interface/api/all_article

代码如下:

import React, { useEffect, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import axios from 'axios';

 function BlogList() {
   const [articles, setArticles] = useState([]);

   useEffect(() => {
     const fetchData = async () => {
       try {
         const response = await axios.get("http://your-api-url/articles"}

");
         console.info("== response.data: ", response.data);
         setArticles(response.data.result); // 将接口返回的数据存储在组件的状态中的 result 属性中
       } catch (error) {
         console.error("请求错误:", error);
       }
     };

     fetchData();
   }, []);

   // 根据创建时间倒序排序
   const sortedArticles = articles.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));

   return (
     <div>
       <h2>美亿的博客</h2>
         {Array.isArray(sortedArticles) && sortedArticles.map(article => (
           <div key={article.id}>
             <div>
               <p>
                 {article.created_at}&nbsp;&nbsp;&nbsp;
                 {article.title}
               </p>
             </div>
           </div>
        ))}
     </div>
   );
 }

export default BlogList;

 在浏览器打开页面 console  里面报错说:

解决方法如下:

1. 使用 Rack 中间件配置:

在 Rails 项目中,你可以使用 Rack 中间件来配置 Access-Control-Allow-Origin 响应头部。创建一个新的中间件文件 config/initializers/cors.rb,并添加以下内容:

# 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]
  end
end

2. 使用控制器过滤器配置:

如果你只需要在特定的控制器或操作中配置 Access-Control-Allow-Origin 响应头部,你可以使用控制器过滤器来实现。

在你的控制器中,你可以添加以下代码:

 class Interface::ApiController < ActionController::Base
   def all_article
     all_article = Article.all.map do |article|
       { :id => article.id,
         :title => article.title,
         :content => article.content,
         :created_at => article.created_at,
        :attachment => article.attachment,
       }
     end
    render :json => { :success =>true, :result => all_article}
  end

  private

  def set_cors_headers
     headers['Access-Control-Allow-Origin'] = '*' # 允许来自任何域的请求,根据需求进行调整
     headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS' # 允许的方法
     headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization' # 允许的请求头部
   end
 end

请注意,将 '*' 用作 Access-Control-Allow-Origin 值可能会存在安全风险,因为它允许来自任何域的请求。在生产环境中,最好将其设置为特定的域名,以提高安全性。

现在你重启服务器,会报错说:

$ bundle exec rails server -p 8888
=> Booting WEBrick
=> Rails 4.2.11.3 application starting in development on http://localhost:8888
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Exiting
/home/meiyi/Blog/blog/config/initializers/cors.rb:1:in `<top (required)>': uninitialized constant Rack::Cors (NameError)
    from /home/meiyi/.asdf/installs/ruby/2.6.9/lib/ruby/gems/2.6.0/gems/railties-4.2.11.3/lib/rails/engine.rb:652:in `block in load_config_initializer'
    from /home/meiyi/.asdf/installs/ruby/2.6.9/lib/ruby/gems/2.6.0/gems/activesupport-4.2.11.3/lib/active_support/notifications.rb:166:in `instrument'
    from /home/meiyi/.asdf/installs/ruby/2.6.9/lib/ruby/gems/2.6.0/gems/railties-4.2.11.3/lib/rails/engine.rb:651:in `load_config_initializer'
    from /home/meiyi/.asdf/installs/ruby/2.6.9/lib/ruby/gems/2.6.0/gems/railties-4.2.11.3/lib/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'
    from /home/meiyi/.asdf/installs/ruby/2.6.9/lib/ruby/gems/2.6.0/gems/railties-4.2.11.3/lib/rails/engine.rb:615:in `each'

是因为你的项目中缺少 rack-cors gem。这个 gem 提供了 Rack 中间件 Rack::Cors,它用于配置跨域资源共享 (CORS)。

1. 在 Gemfile 文件中添加 rack-cors gem

gem 'rack-cors'

2. 运行 $ bundle install 

3. 重启服务器

$ bundle exec rails server -p 8888
=> Booting WEBrick
=> Rails 4.2.11.3 application starting in development on http://localhost:8888
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2023-10-28 19:45:31] INFO  WEBrick 1.4.4
[2023-10-28 19:45:31] INFO  ruby 2.6.9 (2021-11-24) [x86_64-linux]
[2023-10-28 19:45:31] INFO  WEBrick::HTTPServer#start: pid=105768 port=8888

然后在浏览器打开页面,就发现这个问题已经解决了

返回>>

登录

请登录后再发表评论。

评论列表:

目前还没有人发表评论