ChatGPT解决这个技术问题 Extra ChatGPT

在 node.js 中如何发出 HTTP POST 请求?

如何在 node.js 中使用数据发出出站 HTTP POST 请求?

正如 Jed Watson's answer 中所建议的,我强烈建议您使用 request,除非您正在编写低级 API。
您可以只使用 node-fetch,它是本机 fetch JavaScript 方法的实现来发出 HTTP 请求。
这篇文章涵盖了使用请求的基本使用场景。 blog.modulus.io/node.js-tutorial-how-to-use-request-module
上面评论中推荐的请求模块是 deprecated now

M
Michael Schnerring

请求现已弃用。建议您使用替代品

没有特别的顺序,而且非常不完整:

本机 HTTP/S, const https = require('https');

节点获取

axios

得到

超级代理

弯曲

使获取发生

取消获取

小json-http

urllib

Stats comparision Some code examples

原答案:

如果您使用 request 库,这会变得容易得多。

var request = require('request');

request.post(
    'http://www.yoursite.com/formpage',
    { json: { key: 'value' } },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body);
        }
    }
);

除了提供良好的语法之外,它还使 json 请求变得简单,处理 oauth 签名(用于 twitter 等),可以执行多部分表单(例如用于上传文件)和流式传输。

安装请求使用命令 npm install request


{ form: { key: 'value' } } 应替换为 { json: { key: 'value' } } (因为问题不是特定于表单的)。还必须了解'form'和'json'是请求库关键字,而不是自定义数据的一部分(就像最后一条评论可能出现的那样微不足道,我花了一些时间才弄清楚......)
我不断地回到这个问题和答案。它确实应该是问题的“答案”。
纯粹因为这个答案,你应该得到一个金徽章。它比公认的有用得多……而且早在 2012 年就已经存在了?哇
您可能需要通过运行此命令“npm install --save request”来添加依赖项
该库已被弃用。
f
fangzhzh

下面是使用 node.js 向 Google Compiler 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);
  }
});

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


内容长度标头是否计算正确?应该是字节,对吧?
请注意 querystring.stringify() doesn't support nested objects,因此您可能希望改用 qs.stringify()
Content-Length 是字节,不一定是字符串长度(UTF-16 等)。使用 Buffer.byteLength(data) 总是正确的。
对于发送标准 postdata,querystring.stringify 中的对象应该是您自己的数据对象,而不是此答案中显示的垃圾(这可能对基于文件的对象有用?)。我被困了很久...... stackoverflow.com/questions/9768192/… 提供了我的完整解决方案
问题:如果您使用的是 ssl 加密网站,则需要“https”库。您不能只将端口更改为 443。
F
FLAK-ZOSO

您可以使用请求库。 https://www.npmjs.com/package/request

var request = require('request');

要发布 JSON 数据:

var myJSONObject = { ... };
request({
    url: "http://josiahchoi.com/myjson",
    method: "POST",
    json: true,   // <--Very important!!!
    body: myJSONObject
}, function (error, response, body){
    console.log(response);
});

要发布 xml 数据:

var myXMLText = '<xml>...........</xml>'
request({
    url: "http://josiahchoi.com/myjson",
    method: "POST",
    headers: {
        "content-type": "application/xml",  // <--Very important!!!
    },
    body: myXMLText
}, function (error, response, body){
    console.log(response);
});

编辑:截至 2020 年 2 月,requestdeprecated


在他们的文档中审查后。它声明如下: json - 将 body 设置为 JSON 表示值并添加 Content-type: application/json 标头。此外,将响应正文解析为 JSON。这意味着当 json = true 时,它将设置 header 和 json 和 body。否则,不设置标题,并解析为文本。 (如上面的 XML 示例)。这使得请求 API 方便且简单,但第一次很难理解。
从技术上讲,它在他们的文档中,但没有一个示例显示它——只有表单数据。这是大海捞针,因此,这是一个巨大的遗漏,因为这是我在 JS 中使用 ajax 的第二常用方式,当然也是网络上最常用的方式之一。
使用 request.post 比将 POST 指定为方法更好。这里有一些examples from GitHub for using request.post
该库已被弃用。
谢谢你。尝试了不同的 NPM 包,但对我没有任何帮助。谢谢你。您提供了实际的 JSON 与 XML 代码。
m
mpen

简单且无依赖。使用 Promise 以便您可以等待结果。它返回响应正文并且不检查响应状态代码。

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)
})

req,write() 上的 write 方法是做什么用的?
@Ari 写请求的正文... nodejs.org/api/…
谢谢,这个真的很适合 aws lambda,因为现在它总是需要 async await 才能使用。
@mpen 你有没有运行过这段代码?看起来请求示例的参数顺序错误。
@MozartBrocchini 是的,您错过了花括号:-) 我正在使用对象解构。
a
attacomsian

有许多可用的开源库可用于在 Node.js 中发出 HTTP POST 请求。

1. Axios(推荐)

const axios = require('axios');

const data = {
    name: 'John Doe',
    job: 'Content Writer'
};

axios.post('https://reqres.in/api/users', data)
    .then((res) => {
        console.log(`Status: ${res.status}`);
        console.log('Body: ', res.data);
    }).catch((err) => {
        console.error(err);
    });

2. 针

const needle = require('needle');

const data = {
    name: 'John Doe',
    job: 'Content Writer'
};

needle('post', 'https://reqres.in/api/users', data, {json: true})
    .then((res) => {
        console.log(`Status: ${res.statusCode}`);
        console.log('Body: ', res.body);
    }).catch((err) => {
        console.error(err);
    });

3.请求

const request = require('request');

const options = {
    url: 'https://reqres.in/api/users',
    json: true,
    body: {
        name: 'John Doe',
        job: 'Content Writer'
    }
};

request.post(options, (err, res, body) => {
    if (err) {
        return console.log(err);
    }
    console.log(`Status: ${res.statusCode}`);
    console.log(body);
});

4. 原生 HTTPS 模块

const https = require('https');

const data = JSON.stringify({
    name: 'John Doe',
    job: 'Content Writer'
});

const options = {
    hostname: 'reqres.in',
    path: '/api/users',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
    }
};


const req = https.request(options, (res) => {
    let data = '';

    console.log('Status Code:', res.statusCode);

    res.on('data', (chunk) => {
        data += chunk;
    });

    res.on('end', () => {
        console.log('Body: ', JSON.parse(data));
    });

}).on("error", (err) => {
    console.log("Error: ", err.message);
});

req.write(data);
req.end();

有关详细信息,请查看此article


Axios 一英里!
G
Grant Li

我将 RestlerNeedle 用于生产目的。它们都比原生 httprequest 强大得多。可以通过基本身份验证、特殊标头条目甚至上传/下载文件进行请求。

至于 post/get 操作,它们也比使用 httprequest 的原始 ajax 调用简单得多。

needle.post('https://my.app.com/endpoint', {foo:'bar'}, 
    function(err, resp, body){
        console.log(body);
});

我在 needle 之前尝试了 request、node-form-data 和 superagent。在尝试进行多部分表单文件上传时,needle 是唯一对我正常工作的。
L
Levi Roberts

2020 年更新:

我一直非常喜欢phin - 超轻量级 Node.js HTTP 客户端

它可以以两种不同的方式使用。一个带有 Promises(Async/Await),另一个带有传统的回调样式。

通过以下方式安装:npm i phin

直接来自带有 await 的自述文件:

const p = require('phin')

await p({
    url: 'https://ethanent.me',
    method: 'POST',
    data: {
        hey: 'hi'
    }
})

Unpromisifed(回调)风格:

const p = require('phin').unpromisified

p('https://ethanent.me', (err, res) => {
    if (!err) console.log(res.body)
})

截至 2015 年,现在有各种各样不同的库可以用最少的编码完成此任务。我更喜欢用于 HTTP 请求的优雅的轻量级库,除非你绝对需要控制低级 HTTP 的东西。

一个这样的库是 Unirest

要安装它,请使用 npm
$ npm install unirest

再来看看大家都习惯的 Hello, World! 示例。

var unirest = require('unirest');

unirest.post('http://example.com/helloworld')
.header('Accept', 'application/json')
.send({ "Hello": "World!" })
.end(function (response) {
  console.log(response.body);
});


补充:
很多人还建议使用 request [ 2 ]

值得注意的是,在幕后 Unirest 使用 request 库。

Unirest 提供了直接访问请求对象的方法。

例子:

var Request = unirest.get('http://mockbin.com/request');

我发现另一个看起来不错的是github.com/request/request,至少在撰写本文时它似乎比 unirest 更受欢迎
我可以证明要求。这是一个非常好的图书馆。我发现该请求提供了更多低级功能,因此适合将其用于特定应用程序。当我不一定关心低级别的东西时,我发现 Unirest 就足够了。
当它取决于请求时,为什么会认为 unirest 是轻量级的?请求本身有 22 个依赖项,我看不出这是轻量级的
@raphadko 我敢肯定,多年来功能膨胀已经发生。请务必检查我发布答案的时间戳;)
r
ranm8

您还可以使用 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();
    });

它对我不起作用,请在此处查看问题:github.com/ranm8/requestify/issues/2
G
Giulio Roggero
var https = require('https');


/**
 * HOW TO Make an HTTP Call - POST
 */
// do a POST request
// create the JSON object
jsonObject = JSON.stringify({
    "message" : "The web of things is approaching, let do some tests to be ready!",
    "name" : "Test message posted with node.js",
    "caption" : "Some tests with node.js",
    "link" : "http://www.youscada.com",
    "description" : "this is a description",
    "picture" : "http://youscada.com/wp-content/uploads/2012/05/logo2.png",
    "actions" : [ {
        "name" : "youSCADA",
        "link" : "http://www.youscada.com"
    } ]
});

// prepare the header
var postheaders = {
    'Content-Type' : 'application/json',
    'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
};

// the post options
var optionspost = {
    host : 'graph.facebook.com',
    port : 443,
    path : '/youscada/feed?access_token=your_api_key',
    method : 'POST',
    headers : postheaders
};

console.info('Options prepared:');
console.info(optionspost);
console.info('Do the POST call');

// do the POST call
var reqPost = https.request(optionspost, function(res) {
    console.log("statusCode: ", res.statusCode);
    // uncomment it for header details
//  console.log("headers: ", res.headers);

    res.on('data', function(d) {
        console.info('POST result:\n');
        process.stdout.write(d);
        console.info('\n\nPOST completed');
    });
});

// write the json data
reqPost.write(jsonObject);
reqPost.end();
reqPost.on('error', function(e) {
    console.error(e);
});

有没有办法在请求或响应中查看请求帖子正文?
a
aleung

这是我用来发出请求的最简单方法:使用“请求”模块。

安装“请求”模块的命令:

$ npm install request

示例代码:

var request = require('request')

var options = {
  method: 'post',
  body: postData, // Javascript object
  json: true, // Use,If you are sending JSON data
  url: url,
  headers: {
    // Specify headers, If any
  }
}

request(options, function (err, res, body) {
  if (err) {
    console.log('Error :', err)
    return
  }
  console.log(' Body :', body)

});

您还可以使用 Node.js 的内置“http”模块来发出请求。


该库已被弃用。
m
mikemaccana

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

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

还有 node-fetch (https://www.npmjs.com/package/node-fetch),它有一个与浏览器中的 fetch 匹配的 API - 但是这需要手动查询字符串编码,不会自动处理内容类型,或者其他任何工作 superagent 都会这样做。


与 needle、unirest 和 co 相比,它提供了轻量级(superagent:16k,unirest:1M,needle:530K)
P
Pujan

如果您正在寻找基于 Promise 的 HTTP 请求,axios 可以很好地完成它的工作。

  const axios = require('axios');

  axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'})
      .then((response) => console.log(response))
      .catch((error) => console.log(error));

或者

await axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'})

P
Prakhar Sharma

发布 Rest/JSON 请求我们可以简单地使用请求包并将我们必须发送的值保存在 Json 变量中。

首先通过 npm install request --save 在控制台中安装 require 包

var request = require('request');

    var options={
                'key':'28',
                'key1':'value',
                'key2':'value'
                }

    request({
             url:"http://dev.api.ean.com/ean-services/rs/hotel/v3/ping?                      
                 minorRev="+options.key+
                 "&cid="+options.key1+
                 "&apiKey="+options.key2,
             method:"POST",
             json:true},function(error,response,body){
                     console.log(body)
               }
    );

永远不要构建自己的查询字符串。您忽略了正确编码您的值。 Node.js 有一个用于此目的的库:nodejs.org/api/querystring.html
该库已被弃用。
l
loretoparisi

这是我对 POSTGET 的解决方案。

关于 Post 方法:

如果主体是 JSON 对象,那么使用 JSON.stringify 反序列化它并可能相应地设置 Content-Lenght 标头很重要:

      var bodyString=JSON.stringify(body)
      var _headers = {
        'Content-Length': Buffer.byteLength(bodyString)
      };

在将其写入请求之前:

request.write( bodyString );

关于 GetPost 方法:

timeout 可以作为 socket 断开连接发生,因此您必须像这样注册它的处理程序:

request.on('socket', function (socket) {
        socket.setTimeout( self.timeout );
        socket.on('timeout', function() {
            request.abort();
            if(timeout) return timeout( new Error('request timed out') );
        });
    });

request 处理程序是

       request.on('timeout', function () {
          // Timeout happend. Server received request, but not handled it
          // (i.e. doesn't send any response or it took to long).
          // You don't know what happend.
          // It will emit 'error' message as well (with ECONNRESET code).
          req.abort();
          if(timeout) return timeout( new Error('request timed out') );
        });

我强烈建议注册这两个处理程序。

响应正文是分块的,因此您必须在 data 处理程序中连接块:

      var body = '';
      response.on('data', function(d) {
          body += d;
      });

endbody 将包含整个响应正文:

      response.on('end', function() {
        try {
            var jsonResponse=JSON.parse(body);
            if(success) return success( jsonResponse );
        } catch(ex) { // bad json
          if(error) return error(ex.toString());
        }
      });

使用 try...catchtheJSON.parse` 进行包装是安全的,因为您无法确定它实际上是否是格式良好的 json,而且您当时也无法确定它请求。

模块:SimpleAPI

/**
 * Simple POST and GET
 * @author Loreto Parisi (loretoparisi at gmail dot com)
*/
(function() {

  var SimpleAPI;

  SimpleAPI = (function() {

    var qs = require('querystring');

    /**
     * API Object model
     * @author Loreto Parisi (loretoparisi at gmail dot com)
     */
    function SimpleAPI(host,port,timeout,ssl,debug,json) {

      this.host=host;
      this.port=port;
      this.timeout=timeout;
      /** true to use ssl - defaults to true */
      this.ssl=ssl || true;
      /** true to console log */
      this.debug=debug;
      /** true to parse response as json - defaults to true */
      this.json= (typeof(json)!='undefined')?json:true;
      this.requestUrl='';
      if(ssl) { // use ssl
          this.http = require('https');
      } else { // go unsafe, debug only please
          this.http = require('http');
      }
    }

    /**
     * HTTP GET
     * @author Loreto Parisi (loretoparisi at gmail dot com)
     */
    SimpleAPI.prototype.Get = function(path, headers, params, success, error, timeout) {

      var self=this;
      if(params) {
        var queryString=qs.stringify(params);
        if( queryString ) {
          path+="?"+queryString;
        }
      }
      var options = {
        headers : headers,
        hostname: this.host,
        path: path,
        method: 'GET'
      };
      if(this.port && this.port!='80') { // port only if ! 80
        options['port']=this.port;
      }
      if(self.debug) {
        console.log( "SimpleAPI.Get", headers, params, options );
      }
      var request=this.http.get(options, function(response) {

          if(self.debug) { // debug
            console.log( JSON.stringify(response.headers) );
          }

          // Continuously update stream with data
          var body = '';
          response.on('data', function(d) {
              body += d;
          });
          response.on('end', function() {
            try {
              if(self.json) {
                var jsonResponse=JSON.parse(body);
                if(success) return success( jsonResponse );
              }
              else {
                if(success) return success( body );
              }
            } catch(ex) { // bad json
              if(error) return error( ex.toString() );
            }
          });
        });
        request.on('socket', function (socket) {
            socket.setTimeout( self.timeout );
            socket.on('timeout', function() {
                request.abort();
                if(timeout) return timeout( new Error('request timed out') );
            });
        });
        request.on('error', function (e) {
          // General error, i.e.
          //  - ECONNRESET - server closed the socket unexpectedly
          //  - ECONNREFUSED - server did not listen
          //  - HPE_INVALID_VERSION
          //  - HPE_INVALID_STATUS
          //  - ... (other HPE_* codes) - server returned garbage
          console.log(e);
          if(error) return error(e);
        });
        request.on('timeout', function () {
          // Timeout happend. Server received request, but not handled it
          // (i.e. doesn't send any response or it took to long).
          // You don't know what happend.
          // It will emit 'error' message as well (with ECONNRESET code).
          req.abort();
          if(timeout) return timeout( new Error('request timed out') );
        });

        self.requestUrl = (this.ssl?'https':'http') + '://' + request._headers['host'] + request.path;
        if(self.debug) {
          console.log("SimpleAPI.Post",self.requestUrl);
        }
        request.end();
    } //RequestGet

    /**
     * HTTP POST
     * @author Loreto Parisi (loretoparisi at gmail dot com)
     */
    SimpleAPI.prototype.Post = function(path, headers, params, body, success, error, timeout) {
      var self=this;

      if(params) {
        var queryString=qs.stringify(params);
        if( queryString ) {
          path+="?"+queryString;
        }
      }
      var bodyString=JSON.stringify(body)
      var _headers = {
        'Content-Length': Buffer.byteLength(bodyString)
      };
      for (var attrname in headers) { _headers[attrname] = headers[attrname]; }

      var options = {
        headers : _headers,
        hostname: this.host,
        path: path,
        method: 'POST',
        qs : qs.stringify(params)
      };
      if(this.port && this.port!='80') { // port only if ! 80
        options['port']=this.port;
      }
      if(self.debug) {
        console.log( "SimpleAPI.Post\n%s\n%s", JSON.stringify(_headers,null,2), JSON.stringify(options,null,2) );
      }
      if(self.debug) {
        console.log("SimpleAPI.Post body\n%s", JSON.stringify(body,null,2) );
      }
      var request=this.http.request(options, function(response) {

          if(self.debug) { // debug
            console.log( JSON.stringify(response.headers) );
          }

          // Continuously update stream with data
          var body = '';
          response.on('data', function(d) {
              body += d;
          });
          response.on('end', function() {
            try {
                console.log("END", body);
                var jsonResponse=JSON.parse(body);
                if(success) return success( jsonResponse );
            } catch(ex) { // bad json
              if(error) return error(ex.toString());
            }
          });

        });

        request.on('socket', function (socket) {
            socket.setTimeout( self.timeout );
            socket.on('timeout', function() {
                request.abort();
                if(timeout) return timeout( new Error('request timed out') );
            });
        });
        request.on('error', function (e) {
          // General error, i.e.
          //  - ECONNRESET - server closed the socket unexpectedly
          //  - ECONNREFUSED - server did not listen
          //  - HPE_INVALID_VERSION
          //  - HPE_INVALID_STATUS
          //  - ... (other HPE_* codes) - server returned garbage
          console.log(e);
          if(error) return error(e);
        });
        request.on('timeout', function () {
          // Timeout happend. Server received request, but not handled it
          // (i.e. doesn't send any response or it took to long).
          // You don't know what happend.
          // It will emit 'error' message as well (with ECONNRESET code).
          req.abort();
          if(timeout) return timeout( new Error('request timed out') );
        });

        self.requestUrl = (this.ssl?'https':'http') + '://' + request._headers['host'] + request.path;
        if(self.debug) {
          console.log("SimpleAPI.Post",self.requestUrl);
        }

        request.write( bodyString );
        request.end();

    } //RequestPost

    return SimpleAPI;

  })();

  module.exports = SimpleAPI

}).call(this);

用法:

// Parameters
// domain: example.com
// ssl:true, port:80
// timeout: 30 secs
// debug: true
// json response:true
var api = new SimpleAPI('posttestserver.com', 80, 1000 * 10, true, true, true); 

var headers = {
    'Content-Type' : 'application/json',
    'Accept' : 'application/json' 
};
var params = {
  "dir" : "post-test"
};
var method = 'post.php';

api.Post(method, headers, params, body
    , function(response) { // success
       console.log( response );
    }
    , function(error) { // error
      console.log( error.toString() );
    }
    , function(error) { // timeout
       console.log( new Error('timeout error') );
    });

u
user203687

我找到了一个视频,它解释了如何实现这一点:https://www.youtube.com/watch?v=nuw48-u3Yrg

它使用默认的“http”模块以及“querystring”和“stringbuilder”模块。该应用程序从网页中获取两个数字(使用两个文本框),并在提交时返回这两个数字的总和(以及将值保存在文本框中)。这是我在其他任何地方都能找到的最好的例子。

var http = require("http");
var qs = require("querystring");
var StringBuilder = require("stringbuilder");

var port = 9000;

function getCalcHtml(req, resp, data) {
    var sb = new StringBuilder({ newline: "\r\n" });
    sb.appendLine("<html>");
    sb.appendLine(" <body>");
    sb.appendLine("     <form method='post'>");
    sb.appendLine("         <table>");
    sb.appendLine("             <tr>");
    sb.appendLine("                 <td>Enter First No: </td>");

    if (data && data.txtFirstNo) {
        sb.appendLine("                 <td><input type='text' id='txtFirstNo' name='txtFirstNo' value='{0}'/></td>", data.txtFirstNo);
    }
    else {
        sb.appendLine("                 <td><input type='text' id='txtFirstNo' name='txtFirstNo' /></td>");
    }

    sb.appendLine("             </tr>");
    sb.appendLine("             <tr>");
    sb.appendLine("                 <td>Enter Second No: </td>");

    if (data && data.txtSecondNo) {
        sb.appendLine("                 <td><input type='text' id='txtSecondNo' name='txtSecondNo' value='{0}'/></td>", data.txtSecondNo);
    }
    else {
        sb.appendLine("                 <td><input type='text' id='txtSecondNo' name='txtSecondNo' /></td>");
    }

    sb.appendLine("             </tr>");
    sb.appendLine("             <tr>");
    sb.appendLine("                 <td><input type='submit' value='Calculate' /></td>");
    sb.appendLine("             </tr>");

    if (data && data.txtFirstNo && data.txtSecondNo) {
        var sum = parseInt(data.txtFirstNo) + parseInt(data.txtSecondNo);
        sb.appendLine("             <tr>");
        sb.appendLine("                 <td>Sum: {0}</td>", sum);
        sb.appendLine("             </tr>");
    }

    sb.appendLine("         </table>");
    sb.appendLine("     </form>")
    sb.appendLine(" </body>");
    sb.appendLine("</html>");
    sb.build(function (err, result) {
        resp.write(result);
        resp.end();
    });
}

function getCalcForm(req, resp, data) {
    resp.writeHead(200, { "Content-Type": "text/html" });
    getCalcHtml(req, resp, data);
}

function getHome(req, resp) {
    resp.writeHead(200, { "Content-Type": "text/html" });
    resp.write("<html><html><head><title>Home</title></head><body>Want to some calculation? Click <a href='/calc'>here</a></body></html>");
    resp.end();
}

function get404(req, resp) {
    resp.writeHead(404, "Resource Not Found", { "Content-Type": "text/html" });
    resp.write("<html><html><head><title>404</title></head><body>404: Resource not found. Go to <a href='/'>Home</a></body></html>");
    resp.end();
}

function get405(req, resp) {
    resp.writeHead(405, "Method not supported", { "Content-Type": "text/html" });
    resp.write("<html><html><head><title>405</title></head><body>405: Method not supported</body></html>");
    resp.end();
}

http.createServer(function (req, resp) {
    switch (req.method) {
        case "GET":
            if (req.url === "/") {
                getHome(req, resp);
            }
            else if (req.url === "/calc") {
                getCalcForm(req, resp);
            }
            else {
                get404(req, resp);
            }
            break;
        case "POST":
            if (req.url === "/calc") {
                var reqBody = '';
                req.on('data', function (data) {
                    reqBody += data;
                    if (reqBody.length > 1e7) { //10MB
                        resp.writeHead(413, 'Request Entity Too Large', { 'Content-Type': 'text/html' });
                        resp.end('<!doctype html><html><head><title>413</title></head><body>413: Request Entity Too Large</body></html>');
                    }
                });
                req.on('end', function () {
                    var formData = qs.parse(reqBody);
                    getCalcForm(req, resp, formData);
                });
            }
            else {
                get404(req, resp);
            }
            break;
        default:
            get405(req, resp);
            break;
    }
}).listen(port);

m
manyu

在创建一个低级实用程序来处理帖子并获取我的项目请求时,我做了很多努力之后,我决定在这里发布我的努力。在接受的答案中,这里有一个片段,用于发出 http 和 https POST 请求以发送 JSON 数据。

const http = require("http")
const https = require("https")

// Request handler function
let postJSON = (options, postData, callback) => {

    // Serializing JSON
    post_data = JSON.stringify(postData)

    let port = options.port == 443 ? https : http

    // Callback function for the request
    let req = port.request(options, (res) => {
        let output = ''
        res.setEncoding('utf8')

        // Listener to receive data
        res.on('data', (chunk) => {
            output += chunk
        });

        // Listener for intializing callback after receiving complete response
        res.on('end', () => {
            let obj = JSON.parse(output)
            callback(res.statusCode, obj)
        });
    });

   // Handle any errors occurred while making request
    req.on('error', (err) => {
        //res.send('error: ' + err.message)
    });

    // Request is made here, with data as string or buffer
    req.write(post_data)
    // Ending the request
    req.end()
};

let callPost = () => {

    let data = {
        'name': 'Jon',
        'message': 'hello, world'
    }

    let options = {
        host: 'domain.name',       // Your domain name
        port: 443,                 // 443 for https and 80 for http
        path: '/path/to/resource', // Path for the request
        method: 'POST',            
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(data)
        }
    }

    postJSON(options, data, (statusCode, result) => {
        // Handle response
        // Process the received data
    });

}

您从不使用序列化的 post_data 吗?默认情况下,作为 js 对象写入会转换为缓冲区吗?
a
abhinav

Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 Node.js。 Axios 可以轻松地向 REST 端点发送异步 HTTP 请求并执行 CRUD 操作。它可以在纯 JavaScript 中使用,也可以与 Vue 或 React 等库一起使用。

const axios = require('axios');

        var dataToPost = {
          email: "your email",
          password: "your password"
        };

        let axiosConfiguration = {
          headers: {
              'Content-Type': 'application/json;charset=UTF-8',
              "Access-Control-Allow-Origin": "*",
          }
        };

        axios.post('endpoint or url', dataToPost, axiosConfiguration)
        .then((res) => {
          console.log("Response: ", res);
        })
        .catch((err) => {
          console.log("error: ", err);
        })

A
AbolfazlR

在 Node.js 18 中

告别 node-fetch 包、axios 和 request ......现在 fetch API 默认在全局范围内可用。

const res = await fetch('https://nodejs.org/api/documentation.json');
if (res.ok) {
  const data = await res.json();
  console.log(data);
}

我们可以像在浏览器中一样发出请求。

For More Information


S
Skere
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);

request 库已被弃用。
M
Matthew Rideout

发布另一个使用附加配置选项和自定义标头的 axios.post 请求的 axios 示例。

var postData = {电子邮件:“test@test.com”,密码:“密码”};让 axiosConfig = { headers: { 'Content-Type': 'application/json;charset=UTF-8', "Access-Control-Allow-Origin": "*", } }; axios.post('http://:/', postData, axiosConfig) .then((res) => { console.log("RESPONSE RECEIVED: ", res); }) .catch((err) => { console.log("AXIOS ERROR: ", err); })


D
Dave Lee

如果您需要 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);
 });


D
Darryl RN

通过使用 request 依赖项。

简单的解决方案:

 import request from 'request'
 var data = {
        "host":"127.1.1.1",
        "port":9008
    }

request.post( baseUrl + '/peers/connect',
        {
            json: data,  // your payload data placed here
            headers: {
                'X-Api-Key': 'dajzmj6gfuzmbfnhamsbuxivc', // if authentication needed
                'Content-Type': 'application/json' 
            }
        }, function (error, response, body) {
            if (error) {
                callback(error, null)
            } else {
                callback(error, response.body)
            }
        });

request 来自哪里?
该库已被弃用。
v
veeresh yh

Request-Promise 提供基于承诺的响应。 2xx 以外的 http 响应代码将导致 promise 被拒绝。这可以通过设置 options.simple = false 来覆盖

var options = {
  method: 'POST',
  uri: 'http://api.posttestserver.com/post',
  body: {
  some: 'payload'
 },
  json: true // Automatically stringifies the body to JSON
};

rp(options)
.then(function (parsedBody) {
    // POST succeeded...
})
.catch(function (err) {
    // POST failed...
});