dazer
dazer

Reputation: 223

Simple Sinatra routing Json file

I'm writting a simple Sinatra Api that returns a Json file for an specific URL.

this is the code for the server.rb

require 'sinatra'
set :public_folder, 'public'
get '/' do
    'Hello world!'
end

get '/api/spells' do
    content_type :json
    File.read('public/spells.json')
end

However, I kept receiving this error of no such file. Please help! Thank you!

 Errno::ENOENT at /api/spells
 No such file or directory - /spells.json

Upvotes: 1

Views: 2244

Answers (2)

bambery
bambery

Reputation: 310

How are you running the application? If you're using this over rackup or thin, they will not serve files from public/.

You also do not need to set

:public_folder, 'public'

if the folder public/ exists, it will automatically attempt to serve files from that folder. You only need to set that option if you are using a folder that is not public/.

Upvotes: 1

Void Main
Void Main

Reputation: 2291

As the error message shows, it's a problem with your path. According to documentation, by default, the File.read('public/spells.json') will try to find spells.json file in a folder named public/, make sure you put the json file there.

Upvotes: 1

Related Questions