2013-04-24 144 views
25

我想知道,如何通过JSON请求的负载,对于如:{'name' : 'test', 'value' : 'test'}我应该如何通过JSON数据在HTTP POST请求的请求负载

var post_data = {}; 

    var post_options = { 
     host: this._host, 
     path: path, 
     method: 'POST', 
     headers: { 
     Cookie : "session=" + session, 
      'Content-Type': 'application/json', 
      'Content-Length': post_data.length, 
     } 
    }; 

    // 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(); 

感谢您的帮助。 普拉斯

+0

这是否回答你的问题? http://stackoverflow.com/questions/4505809/how-to-post-to-a-request-using-node-js – exclsr 2013-04-24 09:41:07

回答

69

使用request模块

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

我想在这里跟大家来验证一番。是“身体:POSTDATA”正确还是应该POSTDATA被字符串化,如“体:JSON.stringify(POSTDATA); ?谢谢。 – Ric 2016-06-07 23:09:22

+0

@Noah如果我想用'request.post(...)'请问这是怎么变化的?大多数请求客户端应用程序(一个Electron应用程序)将发送包含基于JSON的机构,唯一的例外是多部分机构。我是有想出使用这个库,并在快递(服务器端)应用程序'bodyParser'设置的正确方法的麻烦。我用'app.use(bodyParser.json())'和'app.use(bodyParser.urlencoded({延长:真}));'和请求无法解析,直到我改变了'extended'为false。不知道这是如何与JSON请求相关的,这是我混乱的原因。 – 2016-07-04 01:56:05

+0

Pro解决方案谢谢 – 2017-03-03 23:51:11

1

只是转换为字符串并发送。

post_req.write(JSON.stringify(post_data)); 
0

我想这和它似乎是working.I需要基本身份验证,所以我已包括身份验证,如果你不需要它,你可以将其丢弃。

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