ROR returns JSON with 406 invalid error

When we return the JSON output using render :json =>@profiles , the output will return the desired results with a 406 error. How can I avoid the "406 invalid" error?

+7
source share
3 answers

I am more than sure you have this problem .

Explanations:

Say your controller only returns json responses.

 def action # call respond_to do |format| format.json { render json: results } end end 

This will return json as soon as:

  • /path_to_action.json is called
  • /path_to_action is called with the Content-Type:application/json; headers Content-Type:application/json; and possibly with some other types of headers (e.g. X-Requested-With:XMLHttpRequest )

Otherwise, it returns a 406 Not Acceptable error.

To avoid the problem, if your controller only returns json, write:

 def action # call render json: results end 

otherwise use /path_to_action.json .

+13
source

Just to expand the answer of the arc, and for those who can still stumble upon this problem,

This problem can also occur more specifically when the controller method used for POST HTTP requests displays JSON instead of redirecting. If this method has before_action, and that before the action it tries "redirect_to" instead of rendering JSON, as it was originally intended, an error occurs.

To fix this, just make sure your before_action for this method also displays the response, rather than trying to redirect it.

Example:

 before_action :require_configuration_training def locations_post response = 'hey' render json: response, status: 200 end def require_configuration_training response = 'hi' # Correct below: render json: response, status: 200 # Wrong and will raise error below: # redirect_to another_path end 
+1
source

This happened to me when I had before_action :authenticate_user! in the action of the controller, but it caused it from an unauthorized page.

The page itself tried to send a redirect.

User authentication or removing before_action solved it for me.

0
source

Source: https://habr.com/ru/post/903445/


All Articles