由於項目需求,我需要用nodejs請求某一鏈接去完成一些任何。本來是做PHP的,現在需要把nodejs學習一下。
今天說的就是怎么通過nodejs去請求一個鏈接。
請求一般分為get請求和post請求:
因為網站是http協議的,所以選擇的是:
http.request(options[, callback])
先看get請求的例子:
var http = require('http'); //加載http,因為我們用的是http.request,這個理所當然要加載
(function(){ //創建匿名函數,直接運行 var options={ host:"www.aumalls.com", //host是要訪問的域名,別加http或https path:"/site/testget/name/intrwins", //請求的路徑或參數,參數怎么寫我不用說了吧? method:'get' //請求類型,這里是get } var sendmsg=''; //創建空字符串,用來存放收到的數據 req=http.request(options, function(req) { //發出請求,加上參數,然后有回調函數 req.on("data", function(chunk) { //監聽data,接受數據 sendmsg += chunk; //把接受的數據存入定放的sendmsg }); req.on("end", function(d) { //監聽end事件,請求結束后調用 var list=JSON.parse(sendmsg); //對接受到的數據流進行編碼 console.log(list) //打印出結果 }); }); req.end(); //記住,用request一定要有始有終,如果不結束,程序會一直運行。 })()
被請求端代碼:php
public function testget(){ echo json_encode($_GET); //返回$_GET參數 }
運行nodejs文件 #nodejs test.js
輸出結果:{ controller: 'site', action: 'testget', name: 'intrwins' }
運行成功。。。
先看post的請求的例子:
var url = require('url'); var http = require('http'); var querystring = require('querystring'); (function(){ var sendinfo={ //設置要請求的參數 'who':'intrwins', 'msg':'我在向你發出post請求', } var sendData = querystring.stringify(sendinfo); //對參數編號處理 var options={ host:"www.aumalls.com", path:"/site/testpost", method:'POST', //post請求設置 headers: { //post請求需要設置headers 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(sendData) } } var sendmsg=''; req=http.request(options, function(req) { req.on("data", function(chunk) { sendmsg += chunk; }); req.on("end", function(d) { var list=JSON.parse(sendmsg); console.log(list) }); }); req.write(sendData); //這里一定要記錄,把請求參數定入 req.end(); })()
被請求端php代碼:
public function testpost(){ echo json_encode($_POST); //返回請求參數 }
運行nodejs:#node test.js
運行結果:{ who: 'intrwins', msg: '我在向你發出post請求' }
成功