Ruby on Rails 5.2 - NoMethodErrornil:NilClass 的未定义方法`host':

问题描述

我有一个在 Ruby 2.6.6 上运行的 Ruby on Rails 5.2 应用程序,在以下路径上运行:/api/popups 它给了我 500 内部服务器错误

在生产日志中,我看到以下消息:

Started GET "/api/popups" for IP at 2020-12-30 11:12:30 +0000
INFO -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69] Processing by controller2#index as HTML
INFO -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69] Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.0ms)
FATAL -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69]   
FATAL -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69] NoMethodError (undefined method `host' for nil:NilClass):
FATAL -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69]   
FATAL -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69] app/controllers/concerns/controller1.rb:14:in `popups_for_domain'
[e7a305ff-9d4d-4c83-9572-9ea0708e8f69] app/controllers/controller2.rb:5:in `index'

controller2.rb 索引(第 5 行)如下所示:

def index
    popups = popups_for_domain.includes(:popup_template,:color_schema,:target_sets)
end

controller1.rb 第 14 行包含:

def popups_for_domain
    return @popups_for_domain if @popups_for_domain
    referer_domain = Addressable::URI.parse(request.referer).host.gsub(/^w{3}\./i,'')
    @popups_for_domain = Popup.where(domain: referer_domain)
end

错误从这一行指向宿主函数referer_domain = Addressable::URI.parse(request.referer).host.gsub(/^w{3}\./i,'')

那里出了什么问题,我该如何解决?谢谢。

解决方法

Addressabel::URI.parse returns nil 当 URL 解析为 nilfalse 时。这意味着 - 至少有时 - 您没有 request.referer,您也需要处理这些情况。

这样的事情可能对你有用:

def popups_for_domain
  return @popups_for_domain if @popups_for_domain
  return unless request.referer      

  referer_domain = Addressable::URI.parse(request.referer).host.gsub(/^w{3}\./i,'')
  @popups_for_domain = Popup.where(domain: referer_domain)

结束

,

根据:https://stackoverflow.com/a/6880668/1564840

request.referrer 将/可能在最终用户为空

- entered the site URL in browser address bar itself.
- visited the site by a browser-maintained bookmark.
- visited the site as first page in the window/tab.
- clicked a link in an external application.
- switched from a https URL to a http URL.
- switched from a https URL to a different https URL.
- has security software installed (antivirus/firewall/etc) which strips the referrer from all requests.
- is behind a proxy which strips the referrer from all requests.
- visited the site programmatically (like,curl) without setting the referrer header (searchbots!).

就我而言,我直接在浏览器中调用了 API url,这就是缺少引荐来源网址的原因。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...