簡體   English   中英

$ http請求以角度js傳遞到服務器,而無需在客戶端指定

[英]$http request is passed to the server in angular js without specify it on the client side

我看到了一個使用angular js和JWS auth02metodología進行身份驗證的演示,並對其進行了重新批注...我在服務器端使用express(節點js)定義myApp。

我的問題是這個-在客戶端,我正在執行以下HTTP GET調用:

   $http({url: '/api/restricted', method: 'GET'})
    .success(function (data, status, headers, config) {
      $scope.message = $scope.message + ' ' + data.name;  
    })
    .error(function (data, status, headers, config) {
      alert(data);
    });  

在服務器端,我從http GET請求獲取ID:

app.get('/api/restricted', function (req, res) {
   res.json({
    name: req.user.id
  });
});

並且它正在工作..唯一的問題是我看不到在哪里定義了帶有用戶實體的GET請求...我所看到的只是GET http請求獲得了一個方法和一個URL:

   $http({url: '/api/restricted', method: 'GET'})

那么這個魔術name: req.user.id在哪里name: req.user.id

是從哪里來的?

謝謝...

更多代碼(可能是相對的...):

指數。 html

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Angular Authentication</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <script src="./auth.client.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-cookies.js"></script>
  </head>
  <body ng-app="myApp">
    <div ng-controller="UserCtrl">
      <span ng-show="isAuthenticated">{{welcome}}</span>
      <form ng-show="!isAuthenticated" ng-submit="submit()">
        <input ng-model="user.username" type="text" name="user" placeholder="Username" />
        <input ng-model="user.password" type="password" name="pass" placeholder="Password" />
        <input type="submit" value="Login" />
      </form>
      <div>{{error}}</div>
      <div ng-show="isAuthenticated">
        <a ng-click="callRestricted()" href="">Shh, this is private!</a>
        <br>
        <div>{{message}}</div>
        <a ng-click="logout()" href="">Logout</a>
      </div>
    </div>
  </body>
</html>

客戶端

myApp.controller('UserCtrl', ["$scope", "$http","$window","$cookies", function ($scope, $http, $window,$cookies) {
  $scope.callRestricted = function () {
    $http({url: '/api/restricted', method: 'GET'})
    .success(function (data, status, headers, config) {
      $scope.message = $scope.message + ' ' + data.name;  
    })
    .error(function (data, status, headers, config) {
      alert(data);
    });
  };

myApp.factory('authInterceptor',["$rootScope", "$q","$cookies", 
  function ($rootScope, $q,$cookies) {
    return {
      request: function (config) {
        config.headers = config.headers || {};
        if ($cookies.get('token')) {
          config.headers.Authorization = 'Bearer ' + $cookies.get('token');
        }
        return config;
      },
      responseError: function (rejection) {
        if (rejection.status === 401) {
        // handle the case where the user is not authenticated
      }
      return $q.reject(rejection);
    }
  };
}]);

myApp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
});

並且此代碼在服務器端:

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

var jwt = require('jsonwebtoken'); 
var expressJwt = require('express-jwt'); 

var secret = 'ssasDSA223Sasdas2sdsa23123dvxcgyew231';

var app = express();

// We are going to protect /api routes with JWT
app.use('/api', expressJwt({secret: secret}));

app.use(bodyParser.json());
app.use('/', express.static(__dirname + '/'));

app.use(function(err, req, res, next){
  if (err.constructor.name === 'UnauthorizedError') {
    res.status(401).send('Unauthorized');
  }
});

app.post('/authenticate', function (req, res) {
  //TODO validate req.body.username and req.body.password
  //if is invalid, return 401
  if (!(req.body.username === 'john.doe' && req.body.password === 'foobar')) {
    res.status(401).send('Wrong user or password');
    return;
  }

  var profile = {
    first_name: 'John',
    last_name: 'Doe',
    email: 'John.Doe@gmail.com',
    id: 333333333
  };

  // We are sending the profile inside the token
  var token = jwt.sign(profile, secret, { expiresInMinutes: 60*5 });
  res.json({ token: token });
});

app.get('/api/restricted', function (req, res) {
   res.json({
    name: req.user.id
  });
});

app.listen(8080, function () {
  console.log('listening on http://127.0.0.1:8080');
});

看來您正在使用express-jwt庫。 根據文檔,express-jwt庫是Middleware that validates JsonWebTokens and sets req.user.

當在此行上調用中間件時,會發生這種情況: app.use('/api', expressJwt({secret: secret}));

以角度設置授權數據“ accessToken”的常用方法是設置HTTP標頭,例如

$http.defaults.headers.common['Token'] = token

在angular app的app.run方法中找到它,服務器端通過用戶請求的標頭中提供的訪問令牌識別用戶

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM