使用node express,我无法在ajax帖子后解析req.body。身体通过,但似乎被包裹在另一个对象,防止解析。
profileController.client.js
{"polltitle":"tree","option1":"oak","option2":"willow"}
此时记录的stringifed有效负载看起来是正确的:
ajax: function ajaxByObj (req) {
const url = req.url;
const method = req.method || 'get';
const successCallback = req.success;
const errorCallback = req.error;
const contentType = req.contentType || "application/x-www-form-urlencoded";
const dataType = req.dataType || 'json';
const payload = req.payload || '';
console.log(payload)
let xhr = new XMLHttpRequest();
xhr.open(method, url)
xhr.setRequestHeader("Content-type", contentType)
xhr.responseType = dataType
xhr.onload = function () {
let _this = this
if (this.status == 200) {
successCallback(_this.response)
} else {
errorCallback(_this.response)
}
}
xhr.send(payload)
}
ajaxFunctions.ajax
this.addNewPoll = function(req, res) {
console.log('raw', req.body)
var polldata = JSON.parse(req.body)
console.log('parsed:', polldata)
var title = polldata.polltitle
console.log('title',title)
var fields = []
for (var prop in polldata) {
if (prop != 'poll title') {
fields.push({"name": polldata[prop], "votes": 0})
}
}
以及快递
中路由器的请求处理程序raw { '{"polltitle":"tree","option1":"oak","option2":"willow"}': '' }
记录的原始 req.body数据如下所示
SyntaxError: Unexpected token o
您可以看到数据包含在另一个空字符串值
的对象中当我尝试JSON.parse这个数据时,它会抛出异常
{{1}}
请帮助我找出我做错了什么
谢谢!