Render JSON with header

不羁的心 提交于 2019-12-20 23:27:51

问题


I want to render JSON with the following cors header in my controller:

'Access-Control-Allow-Origin' = '*'.

I tried this:

def my_action
  render(json: some_params)
  response.headers['Access-Control-Allow-Origin'] = '*'
end

but I got an AbstractController::DoubleRenderError. Are there ways to render JSON with headers?


回答1:


You can't set a header after render, because the response is sent. So change the headers after makes no sense and you get this error.

Try:

def my_action
  response.headers['Access-Control-Allow-Origin'] = '*'
  render(json: some_params)
end

UPDATE FOR RAILS 5

As pointed in the question How do you add a custom http header?, after rails 5 you should be setting the headers as following:

response.set_header('HEADER NAME', 'HEADER VALUE')



回答2:


The issue here is that you are rendering the response and then sending the headers.
You should never set headers after the response is sent.

render should be, usually, the last line of your action.

def my_action
  ...
  response.headers['Access-Control-Allow-Origin'] = '*'
  render json: some_params
end


来源:https://stackoverflow.com/questions/35318324/render-json-with-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!