[英]How do I send a .json file as a HTTP POST using node.js?
我是大多數這些概念的新手,所以如果這個問題是微不足道,我道歉。 我正在嘗試編寫一個腳本,該腳本發出一個HTTP POST請求,該請求發送一個包含jsons數組的.json文件。 我正在使用這里找到的npm模塊: https : //github.com/request/request和一個教程,它將引導您使用此處的模塊: http : //samwize.com/2013/08/31/simple-http -get-斜線后請求在節點-點- JS /
這是我到目前為止的代碼:
//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)
}
})
我試圖發送到本地服務器的data.json文件將包含一個jsons數組,格式如下:
[
{
"username": "testuser1",
"firstName": "test",
"lastName": "user1",
"password": "password1'
},
{
"username": "testuser2",
"firstName": "test",
"lastName": "user2",
"password": "password2'
}
]
所以我認為我需要為每個數組元素單獨發出POST請求,但我不清楚如何執行此操作。
這是一個簡單的例子。 正文需要是一個JSON類型,無論項目數量多少,只要JSON格式正確就可以了!
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);
});
要包含json文件,只需像普通一樣使用require函數。
1: const obj = require('./path_to/data.json');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.