Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Axios make call for json response with Rails?

I read and found that axios will make the call for json format to an endpoint, which doesn't seem to be the case here. My endpoint looks like this:

  def create
    @form = Form.new(form_params)
    if @form.save
      respond_to do |format|
        format.html { redirect_to(@form, notice: "Form created successfully") }
        format.json { render json: {message: "Form created successfully"} }
      end
    else
      respond_to do |format|
        format.html { render 'new' }
        format.json { render json: {errors: @form.errors}, status: :unprocessable_entity }
      end

    end
  end

My axios call looks like this:

function instance() {
  return axios.create({
    headers: {'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')},
    'Content-Type':  'application/json',
    responseType: 'json'
  });
}

function post(url, data={}) {
  return instance().post(url, data)
}

here is how I make the call:

post('/forms', {
          form: this.$data
        }).then((response) => {
          console.log("success");
          console.log(response.data);
        }).catch((error) => {
          console.log("errro");
          console.log(error.response);
        })
    }

It works if change /forms to /forms.json, any tip on how to fix this?

like image 908
aks Avatar asked Apr 12 '17 17:04

aks


1 Answers

The correct header key should be Accept. So in reference to your question it should work with: axios.create({headers: {'Accept': 'application/json'}})


Apart of that, it is worth considering to set axios's default headers in a suitable location, like this:

let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
axios.defaults.headers.common['X-CSRF-Token'] = token
axios.defaults.headers.common['Accept'] = 'application/json'
like image 147
Ekkstein Avatar answered Nov 03 '22 23:11

Ekkstein