代码之家  ›  专栏  ›  技术社区  ›  Maiya

使用Vanilla JS XMLHttpRequest对象向Rails发送“post”请求

  •  0
  • Maiya  · 技术社区  · 7 年前

    我正在尝试从我的脚本文件向我的后端Rails 5应用程序发送一个请求(使用普通的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 回复  |  直到 7 年前
        1
  •  2
  •   iwontcode    7 年前

    在发送带有参数的请求的部分,需要对JSON进行字符串化。

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