我如何能使出站HTTP POST请求,与数据,在node.js?


当前回答

如果您需要XML请求,我将与axios库共享我的代码。

const {default: axios} = require('axios');

let xmlString = '<XML>...</XML>';

axios.post('yourURL', xmlString)
 .then((res) => {
   console.log("Status: ", res.status);
   console.log("Body: ", res.data);
 })
 .catch((err) => {
   console.error("Error: ", err);
 });

其他回答

下面是一个使用node.js向谷歌编译器API发出POST请求的例子:

// We need this to build our post string
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');

function PostCode(codestring) {
  // Build the post string from an object
  var post_data = querystring.stringify({
      'compilation_level' : 'ADVANCED_OPTIMIZATIONS',
      'output_format': 'json',
      'output_info': 'compiled_code',
        'warning_level' : 'QUIET',
        'js_code' : codestring
  });

  // An object of options to indicate where to post to
  var post_options = {
      host: 'closure-compiler.appspot.com',
      port: '80',
      path: '/compile',
      method: 'POST',
      headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(post_data)
      }
  };

  // Set up the request
  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
      });
  });

  // post the data
  post_req.write(post_data);
  post_req.end();

}

// This is an async file read
fs.readFile('LinkedList.js', 'utf-8', function (err, data) {
  if (err) {
    // If this were just a small part of the application, you would
    // want to handle this differently, maybe throwing an exception
    // for the caller to handle. Since the file is absolutely essential
    // to the program's functionality, we're going to exit with a fatal
    // error instead.
    console.log("FATAL An error occurred trying to read in the file: " + err);
    process.exit(-2);
  }
  // Make sure there's data before we post it
  if(data) {
    PostCode(data);
  }
  else {
    console.log("No data to post");
    process.exit(-1);
  }
});

我已经更新了代码,以展示如何从文件中发布数据,而不是硬编码的字符串。它使用异步文件系统。readFile命令来实现这一点,在成功读取后发布实际代码。如果出现错误,则抛出错误,如果没有数据,则进程退出,并显示一个负值以指示失败。

let request = require('request');
let jsonObj = {};
request({
    url: "https://myapii.com/sendJsonData",
    method: "POST",
    json: true,
    body: jsonObj
    }, function (error, resp, body){
       console.log(resp);
});

或者你可以使用这个库:

let axios = require("axios");
let jsonObj = {};

const myJsonAPI = axios.create({
   baseURL: 'https://myapii.com',
   timeout: 120*1000
});

let response = await myJsonAPI.post("sendJsonData",jsonobj).catch(e=>{
    res.json(e);
});
console.log(response);

我喜欢超级代理的简单性(https://github.com/visionmedia/superagent)。节点和浏览器上的API相同。

;(async function() {
  var response = await superagent.post('http://127.0.0.1:8125/', {age: 2})
  console.log(response)
})

还有节点获取(https://www.npmjs.com/package/node-fetch),它有一个API来匹配从浏览器获取-然而这需要手动查询字符串编码,不能自动处理内容类型,或者超级代理所做的任何其他工作。

简单且无依赖。使用承诺,让你可以等待结果。它返回响应体,不检查响应状态代码。

const https = require('https');

function httpsPost({body, ...options}) {
    return new Promise((resolve,reject) => {
        const req = https.request({
            method: 'POST',
            ...options,
        }, res => {
            const chunks = [];
            res.on('data', data => chunks.push(data))
            res.on('end', () => {
                let resBody = Buffer.concat(chunks);
                switch(res.headers['content-type']) {
                    case 'application/json':
                        resBody = JSON.parse(resBody);
                        break;
                }
                resolve(resBody)
            })
        })
        req.on('error',reject);
        if(body) {
            req.write(body);
        }
        req.end();
    })
}

用法:

async function main() {
    const res = await httpsPost({
        hostname: 'sentry.io',
        path: `/api/0/organizations/org/releases/${changesetId}/deploys/`,
        headers: {
            'Authorization': `Bearer ${process.env.SENTRY_AUTH_TOKEN}`,
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            environment: isLive ? 'production' : 'demo',
        })
    })
}

main().catch(err => {
    console.log(err)
})

你也可以使用Requestify,这是我为nodeJS +编写的一个非常酷而简单的HTTP客户端,它支持缓存。

只需要做以下几点:

    var requestify = require('requestify');

    requestify.post('http://example.com', {
        hello: 'world'
    })
    .then(function(response) {
        // Get the response body (JSON parsed or jQuery object for XMLs)
        response.getBody();
    });