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

前端 未结 4 1057
猫巷女王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条回答
  •  Happy的楠姐
    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.

    
    
    

    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",

提交回复
热议问题