2016-08-05 63 views
2

我試過了,但是出現錯誤。如何在nodejs中設置用戶代理?

http.get({ url: 'http://www.panda.tv/ajax_chatinfo?roomid=89757', 
    agent: 'Mozilla/5.0' }, function(res) { 
    res.on('data', function(chunk) { 
     doSomething(); 
    }); 
}); 

我閱讀了API文檔,但是我沒有找到關於如何創建的任何內容。

當我運行代碼,我得到以下錯誤:

_http_client.js:158 
    self.agent.addRequest(self, options); 
      ^

TypeError: self.agent.addRequest is not a function 
    at new ClientRequest (_http_client.js:158:16) 
    at Object.exports.request (http.js:31:10) 

    at Object.exports.get (http.js:35:21) 
    at getChatInfo (/home/zeek/Documents/pandatv/node/app.js:5:10) 
    at Object.<anonymous> (/home/zeek/Documents/pandatv/node/app.js:153:1) 
    at Module._compile (module.js:541:32) 
    at Object.Module._extensions..js (module.js:550:10) 
    at Module.load (module.js:458:32) 
    at tryModuleLoad (module.js:417:12) 
    at Function.Module._load (module.js:409:3) 
+1

什麼是錯誤? –

+0

請向我們展示錯誤,請閱讀[ask]和[mcve] – xenteros

+0

您設置的屬性'agent'不是'user-agent'閱讀文檔 – evilive

回答

5
const options = { 
    hostname: 'www.panda.tv', 
    path: 'ajax_chatinfo?roomid=89757', 
    headers: { 'User-Agent': 'Mozilla/5.0' } 
}; 

http.get(options, function(res) { 
    res.on('data', function(chunk) { console.log(chunk) }); 
}); 

考慮未來NPM模塊requestsuperagent,他們會幫你同處理HTTP請求。如果您需要示例,請留下評論,但我相信您會從文檔中獲得它。 GL。

+0

' events.js:160 throw er; //未處理 '錯誤' 事件 ^ 錯誤:連接ECONNREFUSED 127.0.0.1:80 在Object.exports._errnoException(util.js中:1008:11) 在exports._exceptionWithHostPort(util.js中:1031:20) at TCPConnectWrap.afterConnect [as oncomplete](net.js:1080:14)' – user3130007

+0

我複製了你的參數,但是沒有'url'參數。我確實更新了答案。讓我知道如果它確定。 – evilive

+0

在瀏覽器中運行url獲取json。 – user3130007