2
votes

I have a rails API in Rails 5.2 and a frontend in Vuejs, using Axios to request API. When I request with postman on route

[GET] http://localhost:3000/foo

I get the expected JSON response.

But when I request with Axios :

import axios from 'axios'

export default {
  getAll () {
    return axios.get('http://localhost:3000/foo', {
      headers: { 'Content-Type': 'application/json' }
    })
  }
}

I got this response from the server :

CleanwalksController#index is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []

I have the following config/cors.rb :

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

I got the same issue when I try to access to http://localhost:3000/foo directly.

Here is my controller :

class FooController < ApplicationController

  def index
    @foo = foo.all
  end

end
2
Have you tried calling localhost:3000/foo.json to force the request to use the JSON variant (rather than relying on the header)? - Phil

2 Answers

3
votes

I think your problem comes from your view, do you have a file named index.html.erb. Otherwise, you can define multiple response format as following :

class FooController < ApplicationController

def index
  @foo = foo.all
  respond_to do |format|
    format.html { render :index }
    format.json { render json: @foo, status: 200 }
  end
end

end
1
votes

I was having the exact same issue. Everything worked perfectly in my specs and in postman, but for some reason I was getting a 406 with vue/axios.

After much hair pulling I discovered a typo in my routes file:

namespace :v1, default: { format: :json } do

It should have been defaults (plural)

namespace :v1, defaults: { format: :json } do