[Nuxt / Rails] POST implementation using axios and devise_token_auth

When POSTing using axios and devise_token_auth with Nuxt.js and Ruby on Rails, I got stuck in a simple way, so I will summarize it with a memorandum.

Implementation on the Ruby on Rails side

The settings of devise_token_auth are omitted.

The following URL was helpful, so it may be good to see it.

https://github.com/lynndylanhurley/devise_token_auth https://qiita.com/Masahiro_T/items/6bc49a625b437a7c2f45 https://sainu.hatenablog.jp/entry/2018/08/11/194319

Since we have introduced FormObject, we will include that as well.

articles_controller.rb


class ArticlesController < ApplicationController
  def create
    @article = ArticleForm.new(article_params).save
    if @article
      #abridgement
    end
  end

  private

  def article_params
    json_request = ActionController::Parameters.new(JSON.parse(request.body.read))
    json_request.permit(
      :title,
      :description,
    ).merge(user_id: current_user.id)
  end
end

articles_form.rb


class ArticleForm
  include ActiveModel::Model
  attr_reader :title, :description

  validates :title, presence: true, length: { maximum: 50 }
  validates :description, length: { maximum: 300 }

  def initialize(article_params)
    @article = article_params
  end

  def save
    return false if valid?
    Article.create(@article)

    true
  end
end

Now you are ready to POST.

Supplement

Since I was supposed to mess with Json when POSTed, I had to write a process to parse Json. (I was really into it here.)

def article_params
  json_request = ActionController::Parameters.new(JSON.parse(request.body.read))
  json_request.permit(
    :title,
    :description,
  ).merge(user_id: current_user.id)
end

I've saved it in the following article (or rather, copy the Parse part of Json), so I'll post it.

http://tabunmuri.hatenablog.com/entry/2015/07/02/rails%E3%81%A7json%E3%81%AB%E3%80%81permit%E3%81%A7%E8%A6%81%E7%B4%A0%E3%83%81%E3%82%A7%E3%83%83%E3%82%AF%E3%81%97%E3%81%9F%E3%81%84%E6%99%82%E3%81%AE%E6%96%B9%E6%B3%95

Implementation on the Nuxt.js side

I will omit the implementation written in Component and cut out only the implementation of the POSTed part with axios that is done in Vuex.

article.js


export const actions = {
  async postArticle({ dispatch }, article) {
    await this.$axios
      .post('/articles', article, {
        headers: {
          'Content-Type': 'multipart/form-data', //For the assumption of sending thumbnail images
          'access-token': this.state.user.userToken.accessToken,
          client: this.state.user.userToken.client,
          uid: this.state.user.userToken.uid,
        },
      })
      .then(() => dispatch('getArticleList'))
      .catch((error) => console.log(error))
  },
}

I packed the token of devise_token_auth in a cookie and wrote it to Vuex at the time of nuxtServerInit, so that the Token can be inserted in the header at the time of request.

By the way, although it is not Ruby on Rails, it has a similar implementation when using GO echo, and the memorandum is summarized below.

https://qiita.com/arthur_foreign/items/fadd784610d764419786

Recommended Posts

[Nuxt / Rails] POST implementation using axios and devise_token_auth
[Rails] Implementation of automatic address input using jpostal and jp_prefecture
[Rails] [jQuery] Asynchronous like function implementation using remote: true and js.erb
[Rails] Implementation of tag function using acts-as-taggable-on and tag input completion function using tag-it
Implementation of tabs using TabLayout and ViewPager
[Rails] Implementation of search function using gem's ransack
[Rails 6] Implementation of inquiry function using Action Mailer
[Rails] Implementation of image enlargement function using lightbox2
[Rails] Schedule management using Full Calendar Yesterday's implementation
[Rails] Implementation of batch processing using whenever (gem)
[Rails] Implementation of PV number ranking using impressionist
[Rails] Implementation of image slide show using Bootstrap 3
Rails and FormData
rails + devise + devise_token_auth
[Rails] Implementation of drag and drop function (with effect)
[Rails] Implementation of multi-layer category function using ancestry "Preparation"
[Rails] Implementation of multi-layer category function using ancestry "seed"
Using PAY.JP API with Rails ~ Implementation Preparation ~ (payjp.js v2)
Calendar implementation and conditional branching in Rails Gem simple calendar
[Rails] Create sitemap using sitemap_generator and deploy to GAE
[Rails] Google, Twitter, Facebook authentication using Devise and Omniauth
Try to implement tagging function using rails and js
Building a bulletin board API with authentication authorization with Rails 6 Validation and test implementation of # 4 post