我需要拦截 http 请求以将基本 URL(域 URL)添加到 HTTP 请求并添加用于身份验证(基于令牌)的access_token,模板域与 REST API 域不同,但我的问题是我无法识别请求是针对模板或 REST 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;
}
};
}
]);;
您只需检查请求.html
URL 中的字符串即可。
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;
}
有很多方法可以验证请求,例如检查请求是否具有某些特定于 API 的标头,检查 URI 中是否有模板路径或检查 Abhilash 提到的 URI 扩展。
下面是示例代码:
.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;
}
};
}
]);;