如何在Express中正确发送ID数组 [英] How to send array of ids correctly in express
问题描述
我有如下的ID数组:
var arr = [1, 23, 6];
我需要将此数组发送到服务器,对其进行解析,然后从猫鼬数据库中删除ID.对于我的后端,我正在使用nodejs express.因此,我需要您的建议,如何使用jQuery发送数组以及如何在服务器上解析数组.
I need to send this array to a server, parse it, and remove the ids from a mongoose db. For my backend I'm using nodejs express. So I need your advise how should I send the array by using jQuery and how should I parse it on a server.
推荐答案
好的,请按照以下说明进行操作,您会很好:
Ok, follow this instructions and you are good:
首先,让我们创建节点服务器,我使用Express模块定义HTTP服务器:
first of all, lets create our node server, I'm using the Express module to define the HTTP server:
var fs = require('fs'),
express = require('express'),
app = express();
app.listen(8080);
app.use(express.bodyParser());
app.get('/', function(req, res){
var html = fs.readFileSync('index.html');
res.header("Content-Type", "text/html");
res.send(html);
});
app.post('/deleteIds', function(req, res){
console.log(req.body.arr[0]);
res.json({ success: true });
});
服务器的"/"请求返回一个HTML页面,该页面将创建一个jQuery Ajax请求,这是HTML文件的内容:
The server '/' request returns an HTML page that will create an jQuery Ajax request, Here is the HTML file content:
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
url: 'http://localhost:8080/deleteIds',
type: 'POST',
data: {
arr: [ 1, 2, 3]
},
success: function(data){
console.log(data);
}
});
</script>
</head>
<body>
</body>
</html>
如您所见,html文件中的Ajax请求以POST请求的形式发送,并以一个数组作为数据.服务器中的/deleteIds
express path POST函数侦听并使用req.body.arr
接收该数组,请注意,我正在使用app.use(express.bodyParser());
,如果没有此行,我们将无法从POST请求中获取正文内容.
As you can see, the Ajax request in the html file sent as a POST request with an array as the data, The /deleteIds
express path POST function in the server listens to that and takes the array using req.body.arr
, note that I'm using app.use(express.bodyParser());
, without this line we will not be able to get the body content from the POST request.
就这样..我希望这有助于使用express帮助理解Node + Ajax请求,从这一点上讲,您可以在arr
上运行并对数据进行所需的操作.
This is it.. I hope this is helping understand Node + Ajax requests using express, from this point you can run on the arr
and do what you want with the data.
这篇关于如何在Express中正确发送ID数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!