How should I pass json data in the request payload of http post request

后端 未结 3 646
谎友^
谎友^ 2021-02-05 01:05

I wanted to know, how to pass the json request in the payload, for eg: {\'name\' : \'test\', \'value\' : \'test\'}:

var post_data = {};

var post_op         


        
相关标签:
3条回答
  • 2021-02-05 01:38

    i tried this and it seems to be working.I needed basic auth so i have included auth,if you don't need it you can discard it.

    var value = {email:"",name:""};
    
     var options = {
            url: 'http://localhost:8080/doc/',
            auth: {
                user: username,
                password: password
            },
            method :"POST",
            json : value,
    
        };
    
        request(options, function (err, res, body) {
            if (err) {
                console.dir(err)
                return
            }
            console.dir('headers', res.headers)
            console.dir('status code', res.statusCode)
            console.dir(body)
        });
    
    0 讨论(0)
  • 2021-02-05 01:48

    Just convert to a string and send.

    post_req.write(JSON.stringify(post_data));
    
    0 讨论(0)
  • 2021-02-05 02:01

    Use the request module

    npm install -S request

    var request = require('request')
    
    var postData = {
      name: 'test',
      value: 'test'
    }
    
    var url = 'https://www.example.com'
    var options = {
      method: 'post',
      body: postData,
      json: true,
      url: url
    }
    request(options, function (err, res, body) {
      if (err) {
        console.error('error posting json: ', err)
        throw err
      }
      var headers = res.headers
      var statusCode = res.statusCode
      console.log('headers: ', headers)
      console.log('statusCode: ', statusCode)
      console.log('body: ', body)
    })
    
    0 讨论(0)
提交回复
热议问题