POST data with request module on Node.JS

后端 未结 8 1367
青春惊慌失措
青春惊慌失措 2020-12-07 09:14

This module is \'request https://github.com/mikeal/request

I think i\'m following every step but i\'m missing an argument..

var request = require(\'         


        
相关标签:
8条回答
  • 2020-12-07 09:56

    I have to get the data from a POST method of the PHP code. What worked for me was:

    const querystring = require('querystring');
    const request = require('request');
    
    const link = 'http://your-website-link.com/sample.php';
    let params = { 'A': 'a', 'B': 'b' };
    
    params = querystring.stringify(params); // changing into querystring eg 'A=a&B=b'
    
    request.post({
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // important to interect with PHP
      url: link,
      body: params,
    }, function(error, response, body){
      console.log(body);
    });
    
    0 讨论(0)
  • 2020-12-07 09:57

    EDIT: You should check out Needle. It does this for you and supports multipart data, and a lot more.

    I figured out I was missing a header

    var request = require('request');
    request.post({
      headers: {'content-type' : 'application/x-www-form-urlencoded'},
      url:     'http://localhost/test2.php',
      body:    "mes=heydude"
    }, function(error, response, body){
      console.log(body);
    });
    
    0 讨论(0)
  • 2020-12-07 09:57

    If you're posting a json body, dont use the form parameter. Using form will make the arrays into field[0].attribute, field[1].attribute etc. Instead use body like so.

    var jsonDataObj = {'mes': 'hey dude', 'yo': ['im here', 'and here']};
    request.post({
        url: 'https://api.site.com',
        body: jsonDataObj,
        json: true
      }, function(error, response, body){
      console.log(body);
    });
    
    0 讨论(0)
  • 2020-12-07 10:06

    I had to post key value pairs without form and I could do it easily like below:

    var request = require('request');
    
    request({
      url: 'http://localhost/test2.php',
      method: 'POST',
      json: {mes: 'heydude'}
    }, function(error, response, body){
      console.log(body);
    });
    
    0 讨论(0)
  • 2020-12-07 10:08
    var request = require('request');
    request.post('http://localhost/test2.php', 
        {form:{ mes: "heydude" }}, 
        function(error, response, body){
            console.log(body);
    });
    
    0 讨论(0)
  • 2020-12-07 10:08
    1. Install request module, using npm install request

    2. In code:

      var request = require('request');
      var data = '{ "request" : "msg", "data:" {"key1":' + Var1 + ', "key2":' + Var2 + '}}';
      var json_obj = JSON.parse(data);
      request.post({
          headers: {'content-type': 'application/json'},
          url: 'http://localhost/PhpPage.php',
          form: json_obj
      }, function(error, response, body){
        console.log(body)
      });
      
    0 讨论(0)
提交回复
热议问题