[英]How to retrieve data on server side with node.js sent by frontend ajax via post method?
[英]How can I access data sent via AJAX on Node JS server?
我想为我的网站制作一个简单的联系表。 我知道如何使用ajax发送数据,但是我不知道如何在Node JS服务器上访问它。
如果我要使用以下代码发送数据:
var request=new XMLHttpRequest();
request.open("POST","url");
request.send("{value:'10'}");
如何访问传递给服务器的JSON对象中的值?
有很多方法可以做到这一点。
例如,您可以在服务器上创建一个端点,例如使用express http://expressjs.com/ 。 它可能看起来像这样
router.post('/your/url', function(req, res, data) {
var value = req.body.value;
// do cool things with value
res.send('cool');
});
您定义一个将处理您的请求的发布终结点。 使用请求对象,您可以从请求中访问JSON对象
我使用了request_.on("data", function(data_){});
获取我的数据。
如果在我的客户端JS中,我使用request.send("my data");
我可以通过将侦听器添加到Node JS服务器函数中的request_对象中来访问数据。
request_.on("data", function(data_){
console.log(data_);// my data
}
然后,我可以按自己想要的任何方式对数据进行切片,并按自己认为合适的方式使用它。 无需快递。
这是按下联系表单上的“提交”按钮时调用的我的客户端函数:
function clickSubmit(event_) {
var xmlhttprequest = new XMLHttpRequest();
xmlhttprequest.open("POST", "contact");
xmlhttprequest.send("email=" + html.email.value + "&name=" + html.name.value + "&message=" + html.message.value);
}
这是我的Node JS服务器功能:
function handleRequest(request_, response_) {
switch(request_.url) {
case "/contact":
request_.on("data", function(data_) {
console.log("data: " + data_);// Outputs the string sent by AJAX.
});
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.