請問一下在
response.on('end', function() {
// 数据接收完成
result=JSON.parse(body)
console.log("22222222222",result)
});
result內的值,怎麼樣讓createServer可以使用?
完整的程式碼:
var http = require('http');
var https = require('https');
var result;
// 用于请求的选项
var options = {
method: 'POST',
headers:{
'content-Type':'application/json'
}
};
const data = JSON.stringify({
address: '新北市永和區永貞路1號'
})
// 处理响应的回调函数
var callback = function(response){
// 不断更新数据
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
// 数据接收完成
result=JSON.parse(body)
console.log("22222222222",result)
});
}
var svr = http.createServer(function(req, resp) {
console.log(req.method, req.url);
// 向服务端发送请求
var reqZip = https.request('https://c4-tw-nonprod-uat.apigee.net//api/v1/postOffice/postGetZipCode',options, callback);
reqZip.write(data)
reqZip.end();
resp.setHeader("Content-Type", "application/json");
resp.end(JSON.stringify({ date: new Date(), msg:' result.data'}));
});
svr.listen(process.env.PORT || 3000, function() {
console.log('Node HTTP server is listening');
});
後來的解法:
var http = require('http');
var https = require('https');
let result;
// 用於請求的選項
var options = {
host: 'c4-tw-nonprod-uat.apigee.net',
path: '/api/v1/postOffice/postGetZipCode',
method: 'POST',
headers: {
'content-Type': 'application/json; charset=utf-8'
}
};
var svr = http.createServer(function (req, resp) {
var query = require('url').parse(req.url,true).query;
var address = query.address;
console.log("req.address",address)
let respdata=JSON.stringify({'address':address});
// 向服務端發送請求
new Promise((resolve, reject) => {
var reqZip = https.request(options,
function (response) {
// 不斷更新資料
var body = '';
response.on('data', function (data) {
body += data;
});
response.on('end', function () {
// 資料接收完成
result = JSON.parse(body);
resolve();
});
}
);
reqZip.write(respdata);
reqZip.end();
console.log("3", result);
}).then(resolve => {
resp.setHeader("Content-Type", "application/json");
resp.end(JSON.stringify({ date: new Date(), msg: result }));
}).catch((error)=>{
console.error(error);
});
});
svr.listen(process.env.PORT || 3000, function () {
console.log('Node HTTP server is listening');
});