6

I'm having a problem in Sinatra where I can't respond with just a json and I can't find good sinatra docs anywhere, most of things seems outdated.

Anyways, here's the code:

module MemcachedManager
  class App < Sinatra::Base
    register Sinatra::Contrib
    helpers Sinatra::JSON

    get '/' do
      json({ hello: 'world' })
    end
  end
end

MemcachedManager::App.run! if __FILE__ == $0

The response that I do get is:

"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><p>{\"hello\":\"world\"}</p></body></html>\n"

Where it should have been only the json part. Why is it rendering html tags when I didn't ask for it?

4

2 回答 2

6

你看过这篇博文吗?

require 'json'

get '/example.json' do
  content_type :json
  { :key1 => 'value1', :key2 => 'value2' }.to_json
end

我还将其修改为:

get '/example.json', :provides => :json do

停止使用路由的 HTML/XML 调用。由于您使用的是 sinatra-contrib gem,并且由于 Ruby 不需要所有这些括号等,您还可以将您作为示例给出的代码简化为:

require 'sinatra/json'

module MemcachedManager    
  class App < Sinatra::Base
    helpers Sinatra::JSON
    get '/', :provides => :json do
      json hello: 'world'
    end
  end
end

MemcachedManager::App.run! if __FILE__ == $0
于 2013-02-01T00:02:13.997 回答
1

试着放

content_type :json

json(...)通话前

于 2013-01-31T22:05:41.620 回答