$http request在angular js中被传递给服务器,而不需要在客户端指定它
$http request is passed to the server in angular js without specify it on the client side
我看到了一个使用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方法中找到这个服务器端通过请求头中提供的访问令牌识别用户
相关文章:
- 如何在不需要单击按钮的情况下获取选项的值
- Javascript不需要的关闭行为
- Ember.js:liverload服务器不工作
- 删除客户端浏览器上不需要的内容
- 不允许在字段中输入不需要的字符
- 不需要的JSON响应
- 外部解析RSS提要,不需要像谷歌和服务器端那样的任何库
- 返回并重新加载页面时显示不需要的服务器端警报消息
- 如何在HTML5网页中本地保存数据,这样我们就不需要一次又一次地从服务器获取
- 在javascript服务器端连接MySQL,不需要node.js
- 如何在不需要服务器交互或cookie的情况下将值从一个Javascript文件传输到另一个JS文件
- 如何在数据表中加载数据块,而不需要服务器端处理
- 更新文件时不需要重启Node.js中的服务器
- 通过ajax保存表单数据,不需要服务器代码
- 通过jQuery AJAX接收图像并显示图像,而不需要服务器对图像进行base64编码
- CORS, SQLite和JavaScript.任何不需要本地服务器访问实际数据库的方法
- 使用angular-cli在Chrome上运行一个本地构建的angular 2应用,不需要节点服务器
- $http request在angular js中被传递给服务器,而不需要在客户端指定它
- Node.js或其他JS服务器技术是否支持请求之间的本机共享内存而不需要序列化?
- 不需要用Node.js设置本地服务器