Html 使用 AngularJS HTML5 模式重新加载页面会给出错误的 GET 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16569841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reloading the page gives wrong GET request with AngularJS HTML5 mode
提问by Dieter De Mesmaeker
I want to enable HTML5 mode for my app. I have put the following code for the configuration, as shown here:
我想为我的应用启用 HTML5 模式。我已经把下面的代码的配置,如图所示在这里:
return app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix = '!';
$routeProvider.when('/', {
templateUrl: '/views/index.html',
controller: 'indexCtrl'
});
$routeProvider.when('/about',{
templateUrl: '/views/about.html',
controller: 'AboutCtrl'
});
As you can see, I used the $locationProvider.html5mode
and I changed all my links at the ng-href
to exclude the /#/
.
如您所见,我使用了$locationProvider.html5mode
并更改了所有链接ng-href
以排除/#/
.
The Problem
问题
At the moment, I can go to localhost:9000/
and see the index page and navigate to the other pages like localhost:9000/about
.
目前,我可以转到localhost:9000/
并查看索引页面并导航到其他页面,例如localhost:9000/about
.
However, the problem occurs when I refresh the localhost:9000/about
page. I get the following output: Cannot GET /about
但是,刷新localhost:9000/about
页面时出现问题。我得到以下输出:Cannot GET /about
If I look at the network calls:
如果我查看网络调用:
Request URL:localhost:9000/about
Request Method:GET
While if I first go to localhost:9000/
and then click on a button that navigates to /about
I get:
如果我首先转到localhost:9000/
然后单击导航到的按钮,则会/about
得到:
Request URL:http://localhost:9000/views/about.html
Which renders the page perfectly.
完美呈现页面。
How can I enable angular to get the correct page when I refresh?
刷新时如何启用 angular 以获得正确的页面?
采纳答案by James Sharp
From the angular docs
从角度文档
Server side
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
服务器端
使用这种模式需要在服务器端重写 URL,基本上你必须重写所有指向应用程序入口点的链接(例如 index.html)
The reason for this is that when you first visit the page (/about
), e.g. after a refresh, the browser has no way of knowing that this isn't a real URL, so it goes ahead and loads it. However if you have loaded up the root page first, and all the javascript code, then when you navigate to /about
Angular can get in there before the browser tries to hit the server and handle it accordingly
这样做的原因是当您第一次访问页面 ( /about
) 时,例如在刷新后,浏览器无法知道这不是真实的 URL,因此它会继续加载它。但是,如果您首先加载了根页面和所有 javascript 代码,那么当您导航到/about
Angular 时,可以在浏览器尝试访问服务器并相应地处理它之前进入那里
回答by lokers
There are few things to set up so your link in the browser will look like http://yourdomain.com/path
and these are your angular config + server side
需要设置的东西很少,因此您在浏览器中的链接将如下所示http://yourdomain.com/path
,这些是您的 Angular 配置 + 服务器端
1) AngularJS
1) AngularJS
$routeProvider
.when('/path', {
templateUrl: 'path.html',
});
$locationProvider
.html5Mode(true);
2) server side,just put .htaccess
inside your root folder and paste this
2)服务器端,只需放入.htaccess
您的根文件夹中并粘贴它
RewriteEngine On
Options FollowSymLinks
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /#/ [L]
More interesting stuff to read about html5 mode in angularjs and the configuration required per different environment https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5modeAlso this question might help you $location / switching between html5 and hashbang mode / link rewriting
阅读有关 angularjs 中的 html5 模式以及每个不同环境所需的配置的更有趣的内容https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server -to-work-with-html5mode这个问题也可以帮助你$location / 在 html5 和 hashbang 模式之间切换 / 链接重写
回答by Taye
I had a similar problem and I solved it by:
我有一个类似的问题,我通过以下方式解决了它:
Using
<base href="/index.html">
in the index pageUsing a catch all route middleware in my node/Express server as follows (put it after the router):
使用
<base href="/index.html">
在索引页在我的节点/Express 服务器中使用 catch all 路由中间件如下(将它放在路由器之后):
app.use(function(req, res) {
res.sendfile(__dirname + '/Public/index.html');
});
I think that should get you up and running.
我认为这应该能让你开始工作。
If you use an apache server, you might want to mod_rewrite your links. It is not difficult to do. Just a few changes in the config files.
如果您使用 apache 服务器,您可能需要 mod_rewrite 您的链接。做起来并不难。只需在配置文件中进行一些更改。
All that is assuming you have html5mode enabled on angularjs. Now. note that in angular 1.2, declaring a base url is not recommended anymore actually.
所有这些都假设您在 angularjs 上启用了 html5mode。现在。请注意,在 angular 1.2 中,实际上不再推荐声明基本 url。
回答by Oscar
Solution for BrowserSync and Gulp.
BrowserSync 和 Gulp 的解决方案。
From https://github.com/BrowserSync/browser-sync/issues/204#issuecomment-102623643
来自https://github.com/BrowserSync/browser-sync/issues/204#issuecomment-102623643
First install connect-history-api-fallback
:
首先安装connect-history-api-fallback
:
npm --save-dev install connect-history-api-fallback
Then add it to your gulpfile.js:
然后将其添加到您的 gulpfile.js 中:
var historyApiFallback = require('connect-history-api-fallback');
gulp.task('serve', function() {
browserSync.init({
server: {
baseDir: "app",
middleware: [ historyApiFallback() ]
}
});
});
回答by grant
You need to configure your server to rewrite everything to index.html to load the app:
您需要配置您的服务器以将所有内容重写为 index.html 以加载应用程序:
回答by Murat ?orlu
I wrote a simple connect middleware for simulating url-rewriting on grunt projects. https://gist.github.com/muratcorlu/5803655
我写了一个简单的连接中间件来模拟 grunt 项目上的 url 重写。https://gist.github.com/muratcorlu/5803655
You can use like that:
你可以这样使用:
module.exports = function(grunt) {
var urlRewrite = require('grunt-connect-rewrite');
// Project configuration.
grunt.initConfig({
connect: {
server: {
options: {
port: 9001,
base: 'build',
middleware: function(connect, options) {
// Return array of whatever middlewares you want
return [
// redirect all urls to index.html in build folder
urlRewrite('build', 'index.html'),
// Serve static files.
connect.static(options.base),
// Make empty directories browsable.
connect.directory(options.base)
];
}
}
}
}
})
};
回答by Maksood
If you are in .NET stack with MVC with AngularJS, this is what you have to do to remove the '#' from url:
如果您使用 MVC 和 AngularJS 在 .NET 堆栈中,那么您必须执行以下操作才能从 url 中删除“#”:
Set up your base href in your _Layout page:
<head> <base href="/"> </head>
Then, add following in your angular app config :
$locationProvider.html5Mode(true)
Above will remove '#' from url but page refresh won't work e.g. if you are in "yoursite.com/about" page refresh will give you a 404. This is because MVC does not know about angular routing and by MVC pattern it will look for a MVC page for 'about' which does not exists in MVC routing path. Workaround for this is to send all MVC page request to a single MVC view and you can do that by adding a route that catches all url
在 _Layout 页面中设置 base href:
<head> <base href="/"> </head>
然后,在您的 angular 应用程序配置中添加以下内容:
$locationProvider.html5Mode(true)
以上将从 url 中删除“#”,但页面刷新将不起作用,例如,如果您在“yoursite.com/about”中,页面刷新将为您提供 404。这是因为 MVC 不知道角度路由和 MVC 模式将查找“关于”的 MVC 页面,该页面在 MVC 路由路径中不存在。解决方法是将所有 MVC 页面请求发送到单个 MVC 视图,您可以通过添加捕获所有 url 的路由来实现
routes.MapRoute(
name: "App",
url: "{*url}",
defaults: new { controller = "Home", action = "Index" }
);
回答by Jason
IIS URL Rewrite Rule to prevent 404 error after page refresh in html5mode
IIS URL 重写规则以防止 html5mode 中页面刷新后出现 404 错误
For angular running under IIS on Windows
用于在 Windows 上的 IIS 下运行的 angular
<rewrite>
<rules>
<rule name="AngularJS" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
NodeJS / ExpressJS Routes to prevent 404 error after page refresh in html5mode
NodeJS/ExpressJS Routes 防止 html5mode 页面刷新后出现 404 错误
For angular running under Node/Express
用于 Node/Express 下的 angular 运行
var express = require('express');
var path = require('path');
var router = express.Router();
// serve angular front end files from root path
router.use('/', express.static('app', { redirect: false }));
// rewrite virtual urls to angular app to enable refreshing of internal pages
router.get('*', function (req, res, next) {
res.sendFile(path.resolve('app/index.html'));
});
module.exports = router;
More info at: AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors in NodeJS and IIS
更多信息请访问:AngularJS - 在 NodeJS 和 IIS 中启用 HTML5 模式页面刷新而不会出现 404 错误
回答by Brett
As others have mentioned, you need to rewrite routes on the server and set <base href="/"/>
.
正如其他人提到的,您需要在服务器上重写路由并设置<base href="/"/>
.
For gulp-connect
:
对于gulp-connect
:
npm install connect-pushstate
npm install connect-pushstate
var gulp = require('gulp'),
connect = require('gulp-connect'),
pushState = require('connect-pushstate/lib/pushstate').pushState;
...
connect.server({
...
middleware: function (connect, options) {
return [
pushState()
];
}
...
})
....
回答by crlshn
I am using apache (xampp) on my dev environment and apache on the production, add:
我在我的开发环境和生产环境中使用 apache (xampp),添加:
errorDocument 404 /index.html
to the .htaccess solve for me this issue.
到 .htaccess 为我解决这个问题。