Search code examples
ruby-on-railsajaxfile-read

Javascript reading server file GET http://localhost:3000/public/uploads/goodj.json 404 (Not Found)


I am trying to read server file in javascript in ruby on rails project.

$.ajax({
    url: "/public/uploads/goodj.json",
    success: function (file_content) {
        console.log(file_content);
    }
});

And this causes error

GET http://localhost:3000/public/uploads/goodj.json 404 (Not Found)

I think server is recognizing this request as action of controller.

What can I do to make server to understand this is request for reading file?


Solution

  • From Rails guides:

    config.public_file_server.enabled configures Rails to serve static files from the public directory. This option defaults to true, but in the production environment it is set to false because the server software (e.g. NGINX or Apache) used to run the application should serve static files instead. If you are running or testing your app in production mode using WEBrick (it is not recommended to use WEBrick in production) set the option to true. Otherwise, you won't be able to use page caching and request for files that exist under the public directory.

    And the URL should be /uploads/goodj.json, not /public/uploads/goodj.json. So the code snippet should look like that:

    $.ajax({
        url: "/uploads/goodj.json",
        success: function (file_content) {
            console.log(file_content);
        }
    });