我需要拦截http请求添加基本网址(域名网址)到http请求并添加access_token进行身份验证(基于令牌),模板域名来自rest api域,但我的问题是我无法识别请求是否为模板或休息api(数据)。我的代码是:
.config(["$httpProvider", function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.interceptors.push("httpMiddleware");
}
]).factory("httpMiddleware", [
function () {
return {
request: function (config) {
// Need to recognise request is for html template or rest api
var baseUrl = "http://localhost:9926/Api/";
config.url = baseUrl + config.url;
return config;
}
};
}
]);;
答案 0 :(得分:0)
您只需在请求的网址中检查.html
字符串。
request: function (config) {
// Check whether the requested url contains .html
if(config.url.contains('.html'))
{
// request for html templates
}
else{
// request for REST api
// you can also do check for string API in the request url to verify that the request is to our api
}
var baseUrl = "http://localhost:9926/Api/";
config.url = baseUrl + config.url;
return config;
}
答案 1 :(得分:0)
有多种方法可以验证请求,例如检查请求是否包含某些 API特定标头,检查 URI是否包含模板路径,或者检查URI延伸,如Abhilash所述。
以下是示例代码:
.config(["$httpProvider", function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.interceptors.push("httpMiddleware");
}
]).factory("httpMiddleware", [
function () {
return {
request: function (config) {
// Need to recognise request is for html template or rest api
if(config.headers['someAttr'] == valueToCheck){
// or if(config.url.contains('/path/template')){
// or if(config.url.contains('.html')){
var baseUrl = "http://localhost:9926/Api/";
config.url = baseUrl + config.url;
}
return config;
}
};
}
]);;