$http request在angular js中被传递给服务器,而不需要在客户端指定它

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

本文关键字:服务器 不需要 客户端 angular request http js      更新时间:2023-09-26

我看到了一个使用angular js和JWS auth02 metodología进行身份验证的演示,我对它进行了一些调整…我在服务器端使用express (node 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在哪里呢

来自?

谢谢…

更多的代码(可能是相关的…):

索引。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}));

在angular中设置授权数据"accessToken"的常用方法是设置http头,如

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

在angular应用的app.run方法中找到这个服务器端通过请求头中提供的访问令牌识别用户