通过AJAX将数据发布到Rails控制器

时间:2019-05-04 05:52:54

标签: ruby-on-rails ajax transloadit

我正在将Webpack用于我的Rails应用程序。这是我的js和控制器:

const uppy = Uppy()
  .use(Transloadit, {
    params: {
      auth: {
        // To avoid tampering use signatures:
        // https://transloadit.com/docs/api/#authentication
        key: '903df5e32624447a9798d71db0d3b2cf'
      },
      template_id: '3526677204bf44fba43df0f6b68c82ee'
    },
    waitForEncoding: true
  })
  .use(Dashboard, {
      inline: true,
      target: '#drag-drop-area'
  })

uppy.on('transloadit:result', (stepName, result) => {
  //Pass result to my controller and save it to database 
  Rails.ajax({
    url: "/add_images_to_stray",
    type: "POST",
    data: result,
    success: function(data) {
      console.log(data);
    }
  });
}
)

这是我的控制器操作:

def add_images_to_stray
  puts "HELLO WORLD"
end

我收到了以上代码出现的错误:

POST http://localhost:3000/add_images_to_stray 401 (Unauthorized)

因此,我用以下代码更新了AJAX代码:

Rails.ajax({
    url: "/add_images_to_stray",
    type: "POST",
    beforeSend: function (xhr) {
            xhr.setRequestHeader('X-CSRF-Token', token)
        },
    data: result,
    success: function(data) {
      console.log(data);
    }
  });

但是什么也没发生,看来/ add_images_to_stray没有被调用。

0 个答案:

没有答案