简体   繁体   English

用有限的中间件(config.api_only = true)从Rails API应用程序响应脚本?

[英]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 . 我有一个Rails 5应用程序构建为api应用程序 So by default it only responds with json. 因此,默认情况下,它仅以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. 在常规的Rails应用程序中,我只是将脚本放入js.erb文件中。 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 : 它以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服务器仅是api版本,则不能作为脚本请求。

Rails by default responds json. 默认情况下,Rails响应json。

def respond_with_json
   render json: {message: "works"}, status: :ok
end

To request it, you need to request as json dataType: 要请求它,您需要请求为json dataType:

$.ajax({
    url: "https://myapp.example.com/respond_with_json",
    method: "GET",
    dataType: "json",
    success: function(res){
       console.log(res.message)
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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