I have a Rails 5 app build as an api app. So by default it only responds with json.
But for one specific request I need the app to respond with a script.
In a regular Rails app I would simply put my script in a js.erb
file. This won't work here.
If my controller action looks like this:
def respond_with_js
end
and I request the app like this:
$.getScript("https://myapp.example.com/respond_with_js");
it responds with 204 No Content
:
Started GET "/respond_with_js" for 127.0.0.1 at 2018-06-27 20:28:44 +0200
Processing by ApplicationController#respond_with_js as */*
Completed 204 No Content in 0ms
How do I work around this?
You cannot request as script, if rails server is only api version.
Rails by default responds json.
def respond_with_json
render json: {message: "works"}, status: :ok
end
To request it, you need to request as json dataType:
$.ajax({
url: "https://myapp.example.com/respond_with_json",
method: "GET",
dataType: "json",
success: function(res){
console.log(res.message)
}
})