Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

facebook open graph crawler triggering json response in rails actions

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ok so Facebook sends an accepts header of

*/*

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...