如何使用node.js执行请求并添加json文件

嗨,我是新的这个领域,我想做PUT请求,并添加JSON文件。 我有创buildjson文件,我必须执行使用URI的请求和发布请求可以任何一个使用nodejs发布代码,这将是有益的。我创build了这样的put请求文件

var i = 0; var fs = require("fs"); var request = require('request'); var jsonPath = fs.readFileSync('filepath'); // String --> Object var jsonObj = JSON.parse(jsonPath); console.log(changedevicename.call()); for( i = 0; i < jsonObj.ipConfig.length; i++) { var ipv4URI = jsonObj.ipConfig[i].ipv4; // taking ipv4 json file var ipv6URI = jsonObj.ipConfig[i].ipv6; // taking ipv6 json file console.log(ipv4URI); console.log(ipv6URI); rest_service(); //console.log(config[i]); } function rest_service() // should I change this or what { var i = 0; var request = require('request'); var options = { url: 'http://'+'USERNAME'+':'+'PASSWORD'+ '@'+'IPV6'+'URI', method: 'PUT', } { //IP = userGivenIP; //IP = '192.168.0.1'; request( { method:'PUT', url: 'http://'+'USERNAME'+':'+'PASSWORD'+ '@'+'IPV6'+'URI', // headers: { 'Content-Type': 'application/json', // check this, I should change this }, //var ip4Json = JSON.parse(body); // check this, I should change this //console.log('\n\n'+ body + '\n\n'); }, function (error, response, body) // check this, I should change this { if (error!=undefined) { console.log(body); } else { console.log("printerror", error); console.log("IP disabled"); } }); } This code has to be doen dynamically but I am not getting how to do this for put and post request please help me out and mail the code thanks. 

感谢和问候Prathamesh

你可以添加一个body参数来请求。

 const jsonBody = { key1: value1, key2: value2 }; const headers = { authorization: "<token>" }; const options = { method: 'PUT', uri: "some-url", headers: headers, // headers if your api requires body: jsonBody, json: true }; request(options, function(err, response) { // handle err first // do stuff with response }); 

您应该阅读文档: https : //www.npmjs.com/package/request