POST 422 (Unprocessable Entity) in Rails? Due to the routes or the controller?

前端 未结 4 1053
猫巷女王i
猫巷女王i 2020-12-13 04:39

I\'m trying to give users on my website \"points\" or \"credits\" for tweeting about out the brand name.

I have the fancy twitter widget on the appropriate view...

相关标签:
4条回答
  • 2020-12-13 04:51

    If you're including Rails meta data in the HTML header with <%= csrf_meta_tags %> it'll generate the following.

    <meta name="csrf-param" content="authenticity_token" />
    <meta name="csrf-token" content="ihwlaOLL232ipKmWYaqbSZacpJegQqooJ+Cj9fLF2e02NTQw7P/MfQyRuzruCax2xYWtEHWsb/uqiiZP6NWH+Q==" />
    

    You can pull the CRSF token from the meta data and pass it into your async request. Using the native js fetch method you can pass it in as a x-csrf-token header.

    This is a trimmed onSave handler for a React component that enhances a standard Rails form.

      onSaveHandler = (event) => {
        const data = "Foo Bar";
        const metaCsrf = document.querySelector("meta[name='csrf-token']");
        const csrfToken = metaCsrf.getAttribute('content');
        fetch(`/posts/${this.props.post_id}`, {
          method: "PUT",
          body: JSON.stringify({
            content: data
          }),
          headers: {
            'x-csrf-token': csrfToken,
            'content-type': 'application/json',
            'accept': 'application/json'
          },
        }).then(res => {
          console.log("Request complete! response:", res);
        });
      }
    

    Forgery protection is a good idea. This way we stay secure and don't mess with our Rails configuration.

    Using gem 'rails', '~> 5.0.5' & "react": "^16.8.6",

    0 讨论(0)
  • 2020-12-13 04:58

    I got it working!

    I added a...

    skip_before_action :verify_authenticity_token
    

    to the controller.

    The issue was found when checking out the logs and seeing that the CSRF token could not be verified.

    0 讨论(0)
  • 2020-12-13 05:04

    ihaztehcodez(who was last active in 2016 so it won't help nudging him to post an answer) mentions that the skip_before_action :verify_authenticity_token technique is not so secure 'cos you lose forgery protection.

    they mention that the best/secure/'better practise', solutions are mentioned here WARNING: Can't verify CSRF token authenticity rails

    e.g.

    $.ajaxSetup({
      headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
      }
    });
    

    or

    $.ajax({ url: 'YOUR URL HERE',
      type: 'POST',
      beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
      data: 'someData=' + someData,
      success: function(response) {
        $('#someDiv').html(response);
      }
    });
    

    or

    putting this within an ajax request

    headers: {
      'X-Transaction': 'POST Example',
      'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
    },
    
    0 讨论(0)
  • 2020-12-13 05:11

    Same problem I faced. It sorts out after adding

    skip_before_action :verify_authenticity_token

    at the top of your controller where your JS is calling or sending data.

    class UserController < ApplicationController
        skip_before_action :verify_authenticity_token
        def create
        end
    end
    

    as shown in code snippet.

    0 讨论(0)
提交回复
热议问题