【发布时间】:2018-05-21 22:07:51
【问题描述】:
我正在尝试从我的脚本文件向我的后端 rails 5 应用程序发送一个请求(在 vanilla 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 发送到后端”然后发送 JSON 而不是对象。在
params分配之后似乎还有一个额外的),或者只是帖子中的错字? -
看起来你的 params obj 末尾有一个额外的括号,你尝试删除它吗?
-
在 Teemu 和 @Senal 谢谢。转录到该站点时,这是一种类型。在 iwontcode 的回复中解决了 :)
标签: javascript ruby-on-rails ajax xmlhttprequest