用nodejs模擬請求發微博
阿新 • • 發佈:2018-11-21
通過nodejs可以模擬請求傳送微博一共有幾個步驟:
1.首先打開發送微博的視窗,F12開啟瀏覽器除錯視窗,傳送微博
2.捕獲傳送微博的這條請求,如下圖所示:
圖一
圖二
圖三
3.編寫nodejs程式碼
引用http,querystring模組,
postData中的text存放要傳送的微博的具體內容,其他需要傳送的欄位可以從圖三的Form Data中看出
options中存放 hostname,port,path,method,headers。其中headers從圖二的Request Headers中複製即可,注意要用引號包裹成字串,其中一處需要修改'Content-Length':postData.length
comment.js:
var querystring = require('querystring'); var http = require('http'); var postData = querystring.stringify({ 'text': '測試傳送微博!', 'location': 'v6_content_home', 'appkey': '', 'style_type':'1', 'pic_id':'', 'pdetail':'', 'rank':'0', 'rankid':'', 'module':'stissue', 'pub_source':'main_', 'pub_type':'dialog', '_t':'0' }); var options = { hostname: 'www.weibo.com', port: 80, path: '/圖一中看出', method: 'POST', headers: { //從Request Headers中複製 'Content-Length':postData.length, } } var req = http.request(options, function(res) { console.log('Status: ' + res.statusCode); console.log('headers: ' + JSON.stringify(res.headers)); res.on('data', function(chunk) { console.log(Buffer.isBuffer(chunk)); console.log(typeof chunk); }); res.on('end', function() { console.log('傳送微博完畢!'); }); }); req.on('error', function(e) { console.log('Error: ' + e.message); }); req.write(postData); req.end();
4.最後執行命令 node comment.js
返回200,表示成功
重新整理微博頁面,發現這條微博已經發送了