简体   繁体   中英

Respond with script from a Rails API app with limited middleware (config.api_only = true)?

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)
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM