我使用的是Express,它从静态目录加载AngularJS.通常情况下,我会请求http://localhost/,其中Express为我提供index.html和所有正确的Angular文件等.在我的Angular应用程序中,我设置了这些路由,替换ng-view中的内容:

$routeProvider.when('/', {
    templateUrl: '/partials/main.html',
    controller: MainCtrl,
});

$routeProvider.when('/project/:projectId', {
    templateUrl: '/partials/project.html',
    controller: ProjectCtrl,
});

$locationProvider.html5Mode(true);

在我的主页上,我有一个指向<a href="/project/{{project.id}}">的链接,它将成功加载模板,并将我指向http://localhost/project/3或我指定的任何ID.问题是,当我try 将浏览器指向http://localhost/project/3或刷新页面时,请求将发送到Express/Node服务器,后者返回Cannot GET /project/3.

How do I setup my Express routes to accommodate for this? I'm guessing it will require the use of $location in Angular (although I'd prefer to avoid the ugly ?searches and #hashes they use), but I'm clueless about how to go about setting up the Express routes to handle this.

谢谢

推荐答案

我会创建一个catch-all处理程序,运行after条常规路径,发送必要的数据.

app = express();
// your normal configuration like `app.use(express.bodyParser());` here
// ...
app.use(app.router);
app.use(function(req, res) {
  // Use res.sendfile, as it streams instead of reading the file into memory.
  res.sendfile(__dirname + '/public/index.html');
});

app.router是运行所有快速路由(如app.getapp.post)的中间件;通常,Express会自动将其放在中间件链的最末端,但您也可以显式地将其添加到链中,就像我们在这里所做的那样.

然后,如果URL没有被app.router处理,最后一个中间件将把Angular HTML视图发送到客户端.这将发生在any个URL上,而其他中间件无法处理这些URL,因此您的Angular应用程序必须正确处理无效路由.

Node.js相关问答推荐

如何处理EPIPE时,使用axios并期待413响应?

在我的Next.js应用程序中没有正确设置Process.env.NODE_ENV

如何在RavenDB中执行JS索引?

在Node JS中获取控制台选项卡标题

为什么 nginx 不将我的 react index.html 作为后备服务

运行 cypress 测试时如何指定 .env 文件用于我的开发服务器?

为什么后端开发需要单独的服务器?

npm chokidar 触发事件两次

Node.js |如何在微服务之间转发标头?

一个非常奇怪的JavaScript heap out of memory问题

如何使用来自前一阶段的另一个数组的聚合mongoose 在数组中添加字段

无法通过谷歌Electron 表格 api( node js)中的服务帐户访问写入

AWS EC2 npm install 突然很慢

如何在 cypress 测试中进行计算

node.js 中 res.setHeader 和 res.header 的区别

如何使用 Node.js 在服务器端管理多个 JS 文件

Node.js, require.main === 模块

如何在离线时安装 npm 包?

在 Node.js 中写入 CSV

Nodejs将字符串转换为UTF-8