[英]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.