Node.js 通過http呼叫外部介面
阿新 • • 發佈:2018-12-01
通過http.request傳送帶引數的post請求
data:傳送的內容
opt:描述將要發出的請求
data:事件在資料到達時被觸發
end:請求結束時觸發
error:發生錯誤時被觸發
- var http = require("http");
- var data = {username:
- data = JSON.stringify(data);
- //data = require('querystring').stringify(data);
- var opt = {
- host:'localhost',
- port:'8080'
- method:'POST',
- path:'/loginForeign.jspx',
- headers:{
- "Content-Type": 'application/json',
- "Content-Length"
- }
- }
- var body = '';
- var req = http.request(opt, function(res) {
- console.log("response: " + res.statusCode);
- res.on('data',function(data){
- body += data;
- }).on('end', function(){
- console.log(body)
- });
- }).on('error', function(e) {
- console.log("error: " + e.message);
- })
- req.write(data);
- req.end();