【发布时间】:2016-09-16 15:31:24
【问题描述】:
我正在通过在我的 javascript 代码中调用此函数来生成 XMLHTTPRequest,如下所示
ajaxFunctions.ready(ajaxFunctions.ajaxRequest('POST', appUrl+'/new-poll/option-entered', value, function(data){
console.log(data);
}));
然后我发出如下所示的实际 xmlhttp 请求
var ajaxFunctions = {
ready: function ready (fn) {
if (typeof fn !== 'function') {
return;
}
if (document.readyState === 'complete') {
return fn();
}
document.addEventListener('DOMContentLoaded', fn, false);
},
ajaxRequest: function ajaxRequest (method, url, data, callback) {
console.log('Entered the ajaxRequest function');
console.log(data);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
console.log('Making the request');
callback(xmlhttp.response);
}
};
xmlhttp.open(method, url, true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(data);
}
};
但是当我尝试在 POST 路由中访问下面的数据时,我收到一个错误,因为 req.body 似乎未定义。但是,我的 res.json 工作正常,这意味着我没有以正确的方式访问我传递的数据。
app.route('/new-poll/option-entered')
.post(function(req, res){
console.log(req.body.data);
res.json('Hi I can return data');
});
};
我承认这个问题可能只是重复,但我似乎无法找到我应该访问通过 xmlhttp.send() 发送的数据的确切位置!检查 MDN 文档后,我认为它可能附加到 req.body,但返回未定义。那么我到底在哪里找到附加的数据,或者我在发送数据的方式上犯了错误,比如设置了错误的 RequestHeader?
【问题讨论】:
-
你能试试
appUrl的值吗?另外,您要发送什么样的数据? -
抱歉错过了那行,appUrl 在 ajax-functions.js 中设置为 appUrl = window.location.origin;我正在尝试发送纯文本数据
标签: javascript node.js express xmlhttprequest