javascript - 使用 vanilla JS XMLhttprequest 对象向 Rails 发送 "Post"请求

标签 javascript ruby-on-rails ajax xmlhttprequest

我正在尝试从我的脚本文件向我的后端 Rails 5 应用程序发送请求(在普通 JavaScript 中)。

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

最近的尝试(如下)遇到了此解析错误 ActionDispatch::Http::Parameters::ParseError (416: Unexpected token at '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!

最佳答案

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

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

关于javascript - 使用 vanilla JS XMLhttprequest 对象向 Rails 发送 "Post"请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50441998/

相关文章:

ruby-on-rails - rails nginx puma 在/etc/nginx/sites-enabled 中复制上游 "puma"

javascript - 带有 javascript 的 Ajax 无法在 wamp 服务器上运行

javascript - ng-options 在选择中不起作用

ruby-on-rails - 为 Rails 应用程序编写 Rack 中间件时,我有哪些存储选项?

ruby-on-rails - 有时在 Rails 中出现 "Invalid Route Name"错误

javascript - Ajax 表单在提交时复制

java - 为什么 GWT RPC 需要同步接口(interface)?

javascript - 想了解为什么我的代码中的这个 "setInterval"不起作用?

javascript - 颜色不适用于具有噪声函数的 p5.js 示例

javascript - 在 Javascript 中计算平方和