如何使用node.js 'request'使用此HTTP请求

How to use the node.js 'request' library with this http request?

本文关键字:HTTP 请求 request node 何使用 js      更新时间:2023-09-26

我想对网站做一个简单的请求。它应该得到HTML文本,但它得到' '

NPM模块:github.com/request/request

代码:

var fs = require('fs');
var request = require('request');
var options = {
                url:'https://sample.site/phpLoaders/getInventory/getInventory.php',
    encoding : 'utf8',
    gzip : true,
    forever: true,
    headers: {
        'Host': 'sample.site',
        'Connection': 'keep-alive',
        'Content-Length': '58',
        'Cache-Control': 'max-age=0',
        'Accept': '*/*',
        'Origin': 'https://csgosell.com',
        'X-Requested-With': 'XMLHttpRequest',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Referer': 'https://sample.site/',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4',
        'Cookie': 'my-cookies from browser'

    },
    form: {
        stage:'bot',
        steamId:76561198284997423,
        hasBonus:false,
        coins:0
    }
};

request.post(options, 
    function(error, response, body){
        console.log(response.statusCode);
        if (!error) {
            fs.writeFileSync('site.html', body);
        }
        else{
          console.log(error);
        }
     }
);

Chrome请求:https://i.stack.imgur.com/zKQo5.pngNodejs请求:https://i.stack.imgur.com/yH9U3.png

的区别在于标头:权威:csgosell.com:method:POST:path:/phpLoaders/getInventory/getInventory.php:scheme:https

经过一些谷歌搜索,我明白这是http2,并试图把它放在另一个代理的选项,但没有改变。

var spdy = require('spdy');
var agent = spdy.createAgent({
  host: 'sample.site',
  port: 443,
  spdy: {
  ssl: true,
 }

}).once('error', function (err) {
 this.emit(err);
});
options.agent = agent;

为了回答你的问题,我将复制/粘贴我的代码的一部分,使你能够从你的前端应用程序(angularJS)接收到你的后端应用程序(NodeJS)的post请求,以及另一个功能,使你能够从NodeJS反向发送post请求到另一个应用程序(可能会消耗它):

1)接收来自angularJS或其他nodeJS应用程序的请求

 //Import the necessary libraries/declare the necessary objects
var express = require("express");
var myParser = require("body-parser");
var app = express();
// we will need the following imports for the inverse operation
var https = require('https')
var querystring = require('querystring')
      // we need these variables for the post request:

      var Vorname ;
      var Name ;
      var e_mail ;
      var Strasse ;

  app.use(myParser.urlencoded({extended : true}));
  // the post request is send from http://localhost:8080/yourpath
  app.post("/yourpath", function(request, response ) {
      // test the post request
      if (!request.body) return res.sendStatus(400);
      // fill the variables with the user data
       Vorname =request.body.Vorname;
       Name =request.body.Name;
       e_mail =request.body.e_mail;
       Strasse =request.body.Strasse;      
      response.status(200).send(request.body.title);
});

2)相反,从一个nodeJS应用程序向另一个应用程序发送POST请求

    function sendPostRequest()
    {
        // prepare the data that we are going to send to anymotion  
        var jsonData = querystring.stringify({
                "Land": "Land",
                "Vorname": "Vorname",
                "Name": "Name",
                "Strasse": Strasse,
            });
        var post_options = {
            host: 'achref.gassoumi.de',
            port: '443',
            method: 'POST',
            path: '/api/mAPI',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': jsonData.length
            }
        };
        // request object
            var post_req = https.request(post_options, function(res) {
            var result = '';
            res.on('data', function (chunk) {
                result += chunk;
                console.log(result);
            });
            res.on('end', function () {
            // show the result in the console : the thrown result in response of our post request
            console.log(result);
        });
        res.on('error', function (err) {
            // show possible error while receiving the result of our post request
            console.log(err);
        })
        });
        post_req.on('error', function (err) {
            // show error if the post request is not succeed
            console.log(err);
        });
        // post the data
        post_req.write(jsonData);
        post_req.end(); 
// ps : I used a https post request , you could use http if you want but you have to change the imported library and some stuffs in the code
    }

所以最后,我希望这个答案能帮助任何正在寻找如何在nodeJS中获得post请求以及如何从nodeJS应用程序发送post请求的人。

关于如何接收post请求的更多细节,请阅读npm文档中的body-parser库:npm官方网站文档