標籤:自己 ice 方法 join class api ring 運營 install
http建立在TCP協議之上,提供了網路互動的多個api,我根據自己的實踐介紹下request和get的用法,這是底層的方法,用express等架構都可以實現
以極速資料api為例,appkey可以去註冊申請一個
http.request
調用方式 node http_request.js 13800000000
argv 指的是命令列參數
var qs = require(‘querystring‘)var http = require(‘http‘)var tel = process.argv.slice(2).join(‘ ‘).trim()if (!tel.length) { console.log(‘error‘); process.exit()}http.request({ host: ‘api.jisuapi.com‘, path: ‘/shouji/query?‘ + qs.stringify({appkey: ‘???‘, shouji: tel})}, function (res) { var body = ‘‘ res.setEncoding(‘utf8‘); res.on(‘data‘, function (chunk) { body += chunk; }) res.on(‘end‘, function () { var obj = JSON.parse(body) console.log(‘歸屬地‘ + obj.result.city) console.log(‘電訊廠商‘ + obj.result.company) })}).end()
http.get
var qs = require(‘querystring‘)var http = require(‘http‘)var tel = process.argv.slice(2).join(‘ ‘).trim()if (!tel.length) { console.log(‘error‘); process.exit()}http.get({ host: ‘api.jisuapi.com‘, path: ‘/shouji/query?‘ + qs.stringify({appkey: ‘???‘, shouji: tel})}, function (res) { var body = ‘‘ res.setEncoding(‘utf8‘); res.on(‘data‘, function (chunk) { body += chunk; }) res.on(‘end‘, function () { var obj = JSON.parse(body) console.log(‘歸屬地‘ + obj.result.city) console.log(‘電訊廠商‘ + obj.result.company) })})
http.request和http.get 核心的區別在於end()
最後介紹一個模組 superagent
首先安裝 $ npm install superagent
var request = require(‘superagent‘)request.get(‘http://api.jisuapi.com/shouji/query‘) .query({appkey: ‘???‘}) .query({shouji: ‘13800000000‘}) .end(function (err, res) { if (res.ok) { var obj = JSON.parse(res.text) console.log(obj.result.company); } else { console.log(‘error ‘ + res.text); } })
Node之http對象