【问题标题】:How to send a POST request from node.js Express?如何从 node.js Express 发送 POST 请求?
【发布时间】:2015-11-26 11:14:44
【问题描述】:

谁能告诉我从 node.js Express 发送帖子请求的最简单方法,包括如何传递和检索一些数据?我期待类似于 PHP 中的 cURL 的东西。

【问题讨论】:

标签: javascript node.js http post express


【解决方案1】:
var request = require('request');
 function updateClient(postData){
            var clientServerOptions = {
                uri: 'http://'+clientHost+''+clientContext,
                body: JSON.stringify(postData),
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            }
            request(clientServerOptions, function (error, response) {
                console.log(error,response.body);
                return;
            });
        }

为此,您的服务器必须类似于:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())

var port = 9000;

app.post('/sample/put/data', function(req, res) {
    console.log('receiving data ...');
    console.log('body is ',req.body);
    res.send(req.body);
});

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

【讨论】:

    【解决方案2】:

    here 所述的发布请求:

    var http = require('http');
    
    var options = {
      host: 'www.host.com',
      path: '/',
      port: '80',
      method: 'POST'
    };
    
    callback = function(response) {
      var str = ''
      response.on('data', function (chunk) {
        str += chunk;
      });
    
      response.on('end', function () {
        console.log(str);
      });
    }
    
    var req = http.request(options, callback);
    //This is the data we are posting, it needs to be a string or a buffer
    req.write("data");
    req.end();
    

    【讨论】:

    • 哇,流、回调和这样的事情很快就会失控。几乎感觉就像在 C 中工作
    • @MuhammadUmer 我认为如果你使用 promise 接口,回调会变得更简单。我从来没有使用过这个模块,但是有一个 request-promise 实现了对请求对象的承诺
    【解决方案3】:

    你可以这样尝试:

    var request = require('request');
    request.post({ headers: {'content-type' : 'application/json'}
                   , url: <your URL>, body: <req_body in json> }
                   , function(error, response, body){
       console.log(body); 
    }); 
    

    【讨论】:

      【解决方案4】:

      我使用superagent,类似于jQuery。

      这里是docs

      演示如下:

      var sa = require('superagent');
      sa.post('url')
        .send({key: value})
        .end(function(err, res) {
          //TODO
        });
      

      【讨论】:

        【解决方案5】:

        在您的服务器端,代码如下所示:

        var request = require('request');
        
        app.post('/add', function(req, res){
          console.log(req.body);
          request.post(
            {
            url:'http://localhost:6001/add',
            json: {
              unit_name:req.body.unit_name,
              unit_price:req.body.unit_price
                },
            headers: {
                'Content-Type': 'application/json'
            }
            },
          function(error, response, body){
            // console.log(error);
            // console.log(response);
            console.log(body);
            res.send(body);
          });
          // res.send("body");
        });
        

        在接收端服务器代码如下:

        app.post('/add', function(req, res){
        console.log('received request')
        console.log(req.body);
        let adunit = new AdUnit(req.body);
        adunit.save()
        .then(game => {
        res.status(200).json({'adUnit':'AdUnit is added successfully'})
        })
        .catch(err => {
        res.status(400).send('unable to save to database');
        })
        });
        

        Schema 只是两个属性 unit_name 和 unit_price。

        【讨论】:

          猜你喜欢
          • 2020-06-09
          • 1970-01-01
          • 1970-01-01
          • 2022-10-12
          • 2017-05-03
          • 1970-01-01
          • 2019-08-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多