Search code examples
javascriptperldancer

How do I find the path of a data file in Dancer to use in Javascript?


I have the following Javascript segment:

function setLifts() {
     var $lifts = [];
     $.ajax({
          url: 'data/lifts.csv',
          contentType: 'text/csv',
          async: false,
          success: function(text) {
               $lifts = text.split(/\n/);
               return;
          }
     });
     return $lifts;
}

I get the following error when I load the page in Chrome: GET http://127.0.0.1:3000/data/lifts.csv 404 (Not Found)

I have a data directory in the root of my Dancer app. What is the correct path to the csv files?

Thanks!


Solution

  • You need to define a route handler to deal with those and have Dancer send the file to the client. See the Dancer doc.

    Lets the current route handler send a file to the client. Note that the path of the file must be relative to the public directory unless you use the system_path option (see below).

    get '/download/:file' => sub {
        return send_file(params->{file});
    }
    

    The directory data is not included in a standard Dancer installation. You should move the data to public out of security concerns (the doc talks of return send_file('/etc/passwd', system_path => 1);).

    Of course stuff in public can be downloaded without a route handler. The CSS, JS and dispatch.fcgi are in there for starters.