【问题标题】:Serving Angular app using Express使用 Express 服务 Angular 应用程序
【发布时间】:2016-08-01 16:20:59
【问题描述】:

我正在构建一个使用 Express on Node 提供的 Angular 应用程序。

我想做的是当用户访问该站点时,将他们的语言环境附加到 url (domain.com/en-gb)。

然后,无论他们指定什么语言环境,都提供相同的 index.html。

app.use('/', function(req, res) {
   res.sendFile(__dirname + '/public/index.html');
});

我遇到的问题是如何在不考虑请求的情况下提供相同的文件,但也允许不将图像等资产重新路由到 index.html?

谢谢, 哈利

【问题讨论】:

标签: angularjs node.js express


【解决方案1】:

MarcoS 的答案是正确的,我将添加更详细的描述:

app.use(express.static(path.join(__dirname, 'public'))); //this line enables the static serving in the public directory

您的public 目录可能如下:

public 
|_css
|_js
|_images
  |_logo.png

那么,如果你想得到一张图片:

http://localhost:3000/images/logo.png

如果你想在你的 html 页面中显示它:

<img id="logo" src="/images/logo.png"/>

【讨论】:

    【解决方案2】:

    如果您添加类似以下的use 语句,您可以指定图像的位置:

    var staticPathImages = __dirname + '/assets/images';
    app.use(express.static(staticPathImages));
    

    express 将直接提供这些静态资产,无需重新路由到 index.html...

    【讨论】:

    • 我的设置如下: var staticPathImages = __dirname + '/public/assets'; app.use(express.static(staticPathImages)); app.use('/', function(req, res) { res.sendFile(__dirname + '/public/index.html'); });但它仍然为每个文件提供 index.html,知道我做错了什么吗?
    • 答案是“是”... :-) 你确定如果你请求localhost:3000/public/assets/image.jpg(或类似的),index.html 文件会被提供吗?听起来很奇怪...我的设置与您的类似,而且效果很好... :-)
    • 您是否重新启动了服务器?也许它正在运行你的旧代码
    • 终于搞定了,只需要更正路径!谢谢你的帮助! :)
    猜你喜欢
    • 2019-06-25
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    相关资源
    最近更新 更多