我是大多数这些概念的新手,所以如果这个问题很简单,我会道歉。我正在尝试编写一个脚本,该脚本发出一个HTTP POST请求,该请求发送一个包含jsons数组的.json文件。我在这里找到了一个npm模块:https://github.com/request/request 以及一个指导您使用此处的模块的教程: http://samwize.com/2013/08/31/simple-http-get-slash-post-request-in-node-dot-js/
这是我到目前为止的代码:
query[2] = {
$lookup: {
from: "users",
let: {sales_agent: "$sales_agent"},
pipeline: [
{$match: {$expr: {$eq: ['$_id', '$$sales_agent']}}},
{$project: {_id: 1, username: 1, office: 1}},
],
as: "sales_agent"
}
};
query[3] = {
$lookup: {
from: "offices",
let: {office: "$sales_agent.0.office"}, //this value supposed to be come from the previous lookup
pipeline: [
{$match: {$expr: {$eq: ['$_id', '$$office']}}},
{$project: {_id: 1, city: 1,}},
],
as: "office"
}
};
我试图发送到本地服务器的data.json文件将包含一个jsons数组,格式如下:
//var fs = require('fs');
var request = require('request');
// Set the headers
var headers = {
'Content-Type': "stuff",
'x-authorization': "stuff"
}
// Configure the request
var options = {
url: 'http://localhost:8080/users/add',
method: 'POST',
headers: headers,
form: {
'username': 'testuser42',
'firstName': 'test',
'lastName': 'user42',
'password': 'testpassword'
}
}
// Start the request
request(options, function(error, response, body){
if (!error && response.statusCode == 200) {
console.log(body)
}
})
所以我认为我需要为每个数组元素单独发出POST请求,但我不清楚如何执行此操作。
答案 0 :(得分:3)
这是一个简单的例子。正文需要是一个JSON类型,无论项目数量多少,只要JSON格式正确就可以了!你好了!
conf
要包含json文件,只需使用普通的require函数。
1: const obj= {'msg': [
{
"username": "testuser1",
"firstName": "test",
"lastName": "user1",
"password": "password1"
},
{
"username": "testuser2",
"firstName": "test",
"lastName": "user2",
"password": "password2"
}
]};
request.post({
url: 'your website.com',
body: obj,
json: true
}, function(error, response, body){
console.log(body);
});