2017-08-29 115 views
0

我正在開發一個使用Twitter API REST的Web應用程序。我有一個包含Twitter帳戶的頁面和一個用於添加新帳戶的按鈕。當按下該按鈕時,在角控制器中的功能被執行:原因'http:// localhost:3000'因此不允許訪問Twitter API

// Calls token to add a new Twitter user 
 
    $scope.callToken = function() { 
 
     $http.get('/token') 
 
      .then(function (response) { 
 
       console.log(response); 
 
      }); 
 
    };

這是在後端的代碼來服務德請求。它只是重定向到Twitter添加一個新用戶。

// routes.js 
 
var token = express.Router(); 
 

 
\t token.route('/token') 
 
\t \t .get(cuentasCtrl.getToken); 
 
    
 
// Account file 
 

 
exports.getToken = function(req, res) { 
 

 
\t twitter.getRequestToken(function(err, requestToken, requestSecret) { 
 
     if (err) 
 
      res.status(500).send(err); 
 
     else { 
 
      _requestSecret = requestSecret; 
 
      res.setHeader('Access-Control-Allow-Origin', '*'); 
 
      res.redirect("https://api.twitter.com/oauth/authenticate?oauth_token=" + requestToken); 
 
     } 
 
    }); 
 
};

,但我得到了一個錯誤:

Origin 'http://localhost:3000' is therefore not allowed access Twitter API 

我的服務器在本地主機上運行:3000,如果我把本地主機:3000 /令牌在我的瀏覽器沒有問題。我已閱讀using CORS的解決方案並測試了其他瀏覽器,但它對我沒有幫助。我做錯了什麼?

回答

3

您在快速響應中發送的重定向被您在前端使用的http客戶端捕獲,重定向發生在那裏。您處於經典的CORS環境中,當然這不是您可以與Twitter rest API進行交互的方式。

你必須要在節點端的HTTP調用到Twitter(服務器到服務器)或使用客戶端的客戶端庫的推特(https://dev.twitter.com/web/javascript

+0

我認爲最好的辦法是做在節點側的HTTP ,因爲我不想要鏈接中包含的東西。只有我想讓Twitter令牌與用戶API REST進行交互。 –

相關問題