gpt4 book ai didi

javascript - $http请求在Angular js中传递到服务器而不在客户端指定

转载 作者:行者123 更新时间:2023-12-03 06:02:41 25 4
gpt4 key购买 nike

我看到了使用 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'})

那么这个神奇的名称: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}));

关于javascript - $http请求在Angular js中传递到服务器而不在客户端指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39691264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com