发送"发布"使用vanilla JS XMLhttprequest对象请求Rails

时间:2018-05-21 04:26:13

标签: javascript ruby-on-rails ajax xmlhttprequest

我正在尝试从我的脚本文件向我的后端rails 5 app发送请求(使用vanilla javascript)。

我一直在谷歌搜索和阅读MDN,并尝试不同的东西,但仍然无法让它工作。有人能帮忙解决这个问题吗?

最近的尝试(下面)得到了这个解析错误ActionDispatch :: Http :: Parameters :: ParseError(416:' object Object中的意外令牌)'):但是,当我尝试不同的格式时,我仍然会遇到错误,所以我认为我必须遗漏一些东西。我已经查看了其他堆栈溢出问题,但在尝试实现代码时仍然会出错。

    Wrapping the ajax request in a promise:

    function postRequestPromise(uri) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', uri, true);
        xhr.setRequestHeader('Content-Type', 'application/json', 'Accept', 'application/json');
        xhr.onload = function () {
            resolve(xhr.responseText);
         };
            xhr.onerror = function () {
             reject(xhr.statusText);
        };
       //Ive tried params in several formats:
       //this most recent is giving me a parsing error.
       //my goal is to send JSON to the back-end, to be parsed
       const params = { hello: "hello", world: "world" };
            xhr.send(params);
      });
     }

Then sending the post request:
    postRequestPromise('demo/practice_post')
      .then((replyData) => {
        console.log(replyData);
      })
      .catch((err) => {
        console.log("ERROR:", err);
    });

in the controller, I have tried these things:

    class demo < ApplicationController

      def practice_post

        #all three of these attempts either do not log the body or throw errors:
        p request.body.read
        p request.raw.post
        p params

        render plain: "reached demo#practice_post route"
      end
    end

Thank you for any help!

1 个答案:

答案 0 :(得分:2)

使用params发送请求的部分需要进行JSON字符串化。

xhr.send(JSON.stringify(params));