我尝试使用XMLHttpRequest将数据发布到使用ExpressJS制作的服务。
index.js中的服务器端:
app.post('/add',url.add);
url.js中的施维雅方面:
exports.add = function(req, res){
var urlToAdd = req.body;
console.log(urlToAdd);
};
客户方:
<input id="url" required="true"/>
<button id="addButton">Ajouter</button>
JS客户端:
document.getElementById("addButton").addEventListener("click",function(){
var url = document.getElementById("url").value;
var xhr_object = null;
if(window.XMLHttpRequest)
xhr_object = new XMLHttpRequest();
else if(window.ActiveXObject)
xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
else {
alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
return;
}
xhr_object.open("POST", "/add", true);
xhr_object.onreadystatechange = function() {
if(xhr_object.readyState == 4) {
//alert(xhr_object.responseText); // DEBUG MODE
//document.write(xhr_object.responseText);
eval(xhr_object.responseText);
}
return xhr_object.readyState;
}
var param = "url="+url;
xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr_object.send(param);
});
当我想发送数据时,req.body
为undefined
。
答案 0 :(得分:0)
我找到了解决方案 如果你想明确使用POST请求的主体:
app.use(express.bodyParser());
然后你可以这样做:
var urlToAdd = req.body.url;