[英]Sending “Post” Request to Rails with vanilla JS XMLhttprequest object
我正在嘗試從腳本文件向后端Rails 5應用發送請求(使用香草javascript)。
我一直在使用Google搜索和閱讀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!
使用params發送請求的部分需要JSON字符串化。
xhr.send(JSON.stringify(params));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.