简体   繁体   中英

Sending “Post” Request to Rails with vanilla JS XMLhttprequest object

I am trying to send a request (in vanilla javascript) from my script file to my backend rails 5 app.

I have been googling and reading MDN, and trying different things, and still can not get it to work. Is anyone able to help with this?

The most recent attempt (below) got this parsing error ActionDispatch::Http::Parameters::ParseError (416: unexpected token at 'object Object]'): However, when I try different formats, I still get errors, so I'm thinking I must be missing something. I have looked at other stack-overflow questions on this, but still get errors when I try to implement their code.

    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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM