在angularjs中为此HTTP GET添加HTTP基本身份验证 [英] Add HTTP basic authentication to this HTTP GET in angularjs
问题描述
我有一个现有的angularjs代码,可以进行HTTP GET。下面提取的是控制器内的一些相关代码。
I have an existing angularjs code which makes a HTTP GET. Extracted below is some relevant code inside the controller.
.controller('imptViewCtrl', ['$scope', '$http',
function ($scope, $http, ) {
var url = $configuration.webroot + '/impt/list?list=testlist';
$http.get(url).then(function (response) {
tableData = response.data;
});
}]);
我想在HTTP GET中添加HTTP基本身份验证。用户名是 foo
,密码是 bar
。如何做到这一点?
I would like to add HTTP basic authentication to the HTTP GET. The username is foo
and the password is bar
. How can this be done?
推荐答案
因为在基本身份验证中,用户名和密码是由base64解码的。你需要先找一个图书馆来完成这项工作。
Because in basic authentication, the username and password are decode by base64. You need to find a library to do this work for comfortable first.
https://github.com/ninjatronic/ angular-base64
之后,将 base64
加载到您的应用和配置标题中。
After that, load base64
into your app and config headers.
angular
.module('myApp', ['base64'])
.config(function($httpProvider, $base64) {
var auth = $base64.encode("foo:bar");
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + auth;
})
您还可以将身份验证标头提供给 get
如果你愿意,可以单独使用。
You can also provide the authentication header to get
function seprately if you like.
var auth = $base64.encode("foo:bar"),
headers = {"Authorization": "Basic " + auth};
$http.get(url, {headers: headers}).then(function (response) {
这篇关于在angularjs中为此HTTP GET添加HTTP基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!