如何使用AngularJS在IIS上不使用#重写URL?
问题描述:
我在我的web.config中使用了URL重写,它允许我添加不包含#的URL,并允许我使用“name”作为参数来检索URL,例如http://somewebsite.com/name以检索模板文件。当我将这个参数与XMLHTTPRequest一起使用时,页面始终会返回200响应,因为所有URL都基本上由web.config重写进行了验证。有没有一种方法可以在Angular中创建路线,无论文件是否存在,如果不返回自定义404页面,都会返回正确的模板?正如我在我的网站的主页上,我包括一个模板文件,其中显示标题ng视图,然后页脚。当我查看诸如http://somewebsite.com/random这样的页面并且随机不对应于页面时,主页将继续加载而不显示404页面。该页面将继续无间断地加载。如何使用AngularJS在IIS上不使用#重写URL?
========== web.config设置==============
<system.webServer>
<rewrite>
<rules>
<rule name="AngularJS Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
======= Angular Route设置===============
angular.module('main').config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider)
{
//we cannot use services or factories so using the anguar $http provider is
//out of question. Instead we will use a legacy HTTP AJAX request and return
//the status of the said page.
var checkUrlStatus = function(url){
console.log(url + '.asp');
var http = new XMLHttpRequest();
http.open('GET', url, false);
http.send();
console.log(http.status);
return (http.status !== 404 ? url : 'https://somewebsite.com/404.asp');
}
//removes the hash from the urls, but must be used in conjunction with
//the web.config or apache config file
if(window.history && window.history.pushState){
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}
//conditions to route page to the correct template. See if the template
//returns the right resonse with the checkUrl function and proceed forward.
$routeProvider.when('/:param',{
templateUrl: function(params){
//return checkUrlStatus('https://somewebsite.com/pages/accounting.asp');
console.log(checkUrlStatus('https://somewebsite.com/pages/bob.asp') );
//return "/pages/"+url_param+".asp";
}
}).when('/',{
templateUrl: function(){
return 'home.asp';
}
}).otherwise({
templateUrl: function(){
return 'home.asp';
}
})
}
]);
答
问题是我可以向页面发出请求,但是页面总是会返回200,因为URL重写正在返回/或者我的应用程序的主页。所以相反,我创建了一个标签“is-content”作为我页面上的第一个类,当有这个页面的AJAX请求时,我寻找这个类。如果存在,我显示模板的内容,或者显示我的自定义404页面的内容。以下是用于测试此功能的示例:
var checkUrlStatus = function(url){
var http = new XMLHttpRequest();
http.open('GET', url, false);
http.send();
var responseText = http.responseText;
var htmlObject = document.createElement('div');
htmlObject.innerHTML = responseText;
var htmlReturn = htmlObject;
if (htmlReturn.getElementsByClassName('is-content').length > 0){
return url;
}
else {
return 'https://testwebsite.com/pages/404.asp';
}
}
您不能。 URL的“片段标识符”部分不会发送到服务器,因此服务器无法更改它。你必须在客户端脚本中完成。 – Dai
我意识到片段部分没有发送到服务器,这就是为什么我想发送一个ajax请求到请求的文件,看看它是否存在,但是当我这样做时,服务器在检查之前将重写为“/”看看这个文件是否存在,以便在200返回每一个请求。在看到文件是否存在或绕过这个功能之后是否可以重写?我应该寻找一个特殊的ID标签吗? –