【问题标题】:Twitter api returning empty body with node.jsTwitter api使用node.js返回空正文
【发布时间】:2016-06-20 17:29:48
【问题描述】:

我正在尝试访问 twitter api 以从主题标签中获取帖子。我按照仅应用程序身份验证的步骤进行操作。第 2 步是获取我能够做到的不记名令牌。然而,在那一步之后,当我发送一个获取请求以获取推文时,我收到一个空的正文。

在以下代码中,我省略了 API 密钥本身。

    var express = require('express');
    var bodyParser = require('body-parser');

    //var sendNotification = require('./utils/sendNotification.js');
    var request = require('request');
    var app = express();

    app.use(bodyParser.urlencoded({
          extended: true
    }));
    app.use(bodyParser.json());



    function getTweets(){
         request.post({
                headers: {'content-type' : 'application/x-www-form-urlencoded',"Authorization": 'Basic WmR5Tk9tMHJQUlV3VVlwZm1iRDR3eTRCeTpFdVRoZ2FPSEZpNDJsM0h6azlYWjJwaWNCaFA2SFh0RnBDdkNycDN2Zk1zM29TV2NGYw=='},
                url:     'https://api.twitter.com/oauth2/token',
                body: 'grant_type=client_credentials'
         }, function(error, response, body){
                var token =JSON.parse(body)['access_token'];
                console.log("Bearer "+ token);
                request.get({
                      headers: {'Authorization':'Bearer ' + JSON.stringify(token)},
                      url: 'https://api.twitter.com/1.1/search/tweets.json?',
                      body: encodeURIComponent('q=#dubNations')
                },function(e,r,b){
                   console.log(r)
                  console.log(b)
                });
         });

   }

部分输出(响应)是:

     ClientRequest {
    domain: null,
    _events: [Object],
    _eventsCount: 5,
    _maxListeners: undefined,
    output: [],
    outputEncodings: [],
    outputCallbacks: [],
    outputSize: 0,
    writable: true,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: false,
    useChunkedEncodingByDefault: false,
    sendDate: false,
    _removedHeader: [Object],
    _contentLength: null,
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    socket: [Object],
    connection: [Object],
    _header: 'GET /1.1/search/tweets.json? HTTP/1.1\r\nAuthorization: Bearer "AAAAAAAAAAAAAAAAAAAAAMzZvgAAAAAATAmG%2Fj8Hnx3oqys3DqfsfbuSuIU%3DVUfy6IOBmx5QPrvhHybuLSHcG8fE8sO27r1MjX1YZ2Ar4ynwHz"\r\nhost: api.twitter.com\r\ncontent-length: 17\r\nConnection: close\r\n\r\n',
    _headers: [Object],
    _headerNames: [Object],
    _onPendingData: null,
    agent: [Object],
    socketPath: undefined,
    method: 'GET',
    path: '/1.1/search/tweets.json?',
    _ended: true,
    parser: null,
    res: [Circular] },
 ntick: true,
 response: [Circular],
 originalHost: 'api.twitter.com',
 originalHostHeaderName: 'host',
 responseContent: [Circular],
 _ended: true,
 _callbackCalled: true },
 toJSON: [Function: responseToJSON],
 caseless: 
  Caseless {
    dict: 
     { connection: 'close',
      'content-length': '0',
    date: 'Mon, 20 Jun 2016 02:22:03 GMT',
    server: 'tsa_a',
    'x-connection-hash': '6cd802f0e295a3ad66ee45459323b83c' } },
read: [Function],
 body: '' }

如果您需要更多,请询问。

我不确定为什么正文是空的,因为不记名令牌被正确返回,我只是在做一个获取主题标签的请求。

【问题讨论】:

  • 为什么不将 encodeURIComponent('q=#dubNations') 附加到 get 中的 URL 字符串而不是放入正文中。我查看了文档但无法验证这一点,但请求中的 BODY 通常用于发送有关 POST/PUT 的信息。没有得到。

标签: node.js express twitter


【解决方案1】:

您的 GET 请求语法错误(正如@Brant 指出的那样)。您应该使用qs 属性:

request.get({
    headers: {'Authorization':'Bearer ' + JSON.stringify(token)},
    url: 'https://api.twitter.com/1.1/search/tweets.json?',
    json: true,
    qs: {
        q: '#dubNations'
    }
},function(e,r,b){
    console.log(r)
    console.log(b)
});

我还添加了 json: true 属性,因为这将告诉请求将响应解析为 JSON 并将其返回到您的 b 参数中。

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 2018-10-08
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多