Nodejs Ajax twitter Oauth

时间:2016-01-07 06:18:36

标签: node.js twitter twitter-oauth

我的脚本中有一个用于twitter身份验证的ajax调用。它不工作,给我一个错误。如何将用户重定向到Twitter登录,然后使用ajax返回? 我的AJAX代码:

var login = $.ajax({
                                          url: "http://paybyshare.herokuapp.com/twitterlogin",
                                          method: "GET",
                                          data: { shop_name: shopname },
                                          dataType: "json"
                                        });

                                        login.done(function(msg) {
                                            alert("reached")
                                        });

                                        login.fail(function( jqXHR, textStatus ) {
                                          alert( "Request failed: " + textStatus );
                                        });

我的Nodejs代码:

app.get('/twitterlogin',function(req,res){
  twitter.getRequestToken(function(error, requestToken, requestTokenSecret, results){
    if (error) {
     console.log('Error:', error);
    } else {
      //store token and tokenSecret somewhere, you'll need them later; redirect user 
      req.session.requestToken=requestToken;
      req.session.requestTokenSecret=requestTokenSecret;

       var twitter_auth_url = twitter.getAuthUrl(requestToken);

       res.redirect(twitter_auth_url);
    }
  });
});

app.get('/twitter',function(req,res){

  twitter.getAccessToken(req.query.oauth_token, req.session.requestTokenSecret, req.query.oauth_verifier, function(error, accessToken, accessTokenSecret, results) {
    if (error) {
      console.log(error);
    } else {
      req.session.twitter_access_token=accessToken;
      req.session.twitter_access_token_secret=accessTokenSecret;

      twitter.verifyCredentials(accessToken, accessTokenSecret, function(error, data, response) {
          if (error) {
            res.redirect('/twitterlogin');
          } else {
            console.log(data["screen_name"]);
            res.json(data)
          }
        });
    }
  });
});

0 个答案:

没有答案