本文介绍了facebook 打开图形爬虫在 rails 操作中触发 json 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,facebook 爬虫在我的 rails 操作中触发了 json 响应.这会导致操作仅返回对象的 json 表示,而没有正常的 html 标记 + 打开图形标签.我已经用 rails 3.2.6 对此进行了测试.我使用 facebook 开放图调试器来查看刮刀看到的内容:http://developers.facebook.com/tools/debug.

For some reason the facebook crawler is triggering the json response in my rails actions. This causes the action to just return a json representation of the object, without the normal html markup + open graph tags. I have tested this with rails 3.2.6. I use the facebook open graph debugger to see what the scraper is seeing: http://developers.facebook.com/tools/debug.

代码很简单.想象一个对象的简单显示"操作,例如用户.结尾:

The code is very simple. Imagine a simple "show" action for an object, for example a User. It ends with:

respond_to do |format|
  format.js { render :json => @this.to_json }
  format.html
end

facebook 爬虫正在触发 format.js,这会导致无法呈现开放图标签.任何想法为什么会发生这种情况或如何解决它?谢谢.

The facebook crawler is triggering the format.js, which causes the open graph tags to not be rendered. Any ideas why this might happen or how to fix it? Thanks.

推荐答案

好的,所以 Facebook 发送了一个接受标题

Ok so Facebook sends an accepts header of

*/*

由于没有请求特定的格式,rails 只是按顺序进入 response_to 块.如果您首先在 response_to 块中列出您的 js,如下所示,rails 将使用 JSON 响应 facebook open crawler,这将不起作用:

Since no specific format is requested, rails just goes down the respond_to block in order. If you list your js first in the respond_to block like below rails will respond to the facebook open crawler with JSON which will not work:

respond_to do |format|
  format.js { render :json => @this.to_json }
  format.html
end

只需切换顺序,默认情况下 rails 会以 HTML 响应:

Just switch the order so by default rails responds with HTML:

respond_to do |format|
  format.html
  format.js { render :json => @this.to_json }
end

我不知道为什么 Facebook 没有指定他们正在寻找的格式......对我来说似乎很愚蠢.希望这对以后的人有所帮助.

I'm not sure why Facebook does not specify the format they are looking for... seems pretty idiotic to me. Hopefully this is helpful to somebody down the road.

这篇关于facebook 打开图形爬虫在 rails 操作中触发 json 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!