2013-04-24 112 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) 
    });