Отправка запроса «Post» в Rails с ванильным объектом JS XMLhttprequest - PullRequest
0 голосов
/ 21 мая 2018

Я пытаюсь отправить запрос (в vanilla javascript) из моего файла сценария в мое приложение backend rails 5.

Я гуглю и читаю MDN, пробую разные вещи и до сих пор не могу получитьэто на работу.Кто-нибудь может помочь с этим?

Самая последняя попытка (ниже) получила эту ошибку синтаксического анализа ActionDispatch :: Http :: Parameters :: ParseError (416: неожиданный токен в 'объекте объекта]'): Тем не менее,когда я пробую разные форматы, я все еще получаю ошибки, поэтому я думаю, что я что-то упускаю.Я рассмотрел другие вопросы о переполнении стека, но все еще получаю ошибки, когда пытаюсь реализовать их код.

    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 голосов
/ 21 мая 2018

Часть, в которую вы отправляете запрос с параметрами, должна быть в формате JSON.

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