Node之http對象

來源:互聯網
上載者:User

標籤:自己   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對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.