【发布时间】:2018-07-04 18:15:42
【问题描述】:
我的 Angular 项目运行在与我的 API 后端 (asp.net) 不同的端口上。我正在使用代理将所有 http 请求路由到后端网络服务器,如下所示。
{
"/api": {
"target": {
"host": "localhost",
"protocol": "https:",
"port": 5001
},
"secure": false,
"logLevel" : "debug",
"changeOrigin": true
}
}
我的 Angular 项目服务选项是,
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "art-ng-core:build",
"host": "www.artngcore.com",
"port": 8500,
"sslKey": "key.key",
"sslCert": "server.crt"
},
"configurations": {
"production": {
"browserTarget": "art-ng-core:build:production"
}
}
},
我的问题是 API 提供的静态文件,即图像。
<img src={{imagePath}}>
我的后端静态文件位于不同的静态文件夹“SystemData”中,共享路径为“Data”。
假设我有一个带有相对路径的文件:/Data/UserData/test.jpg。如果我提供带有相对路径的src 属性,则图像的URL 将类似于https://www.artngcore.com:8500/Data/UserData/test.jpg,它应该是https://localhost:5001/Data/UserData/test.jpg
如何像处理 Http 调用一样代理静态文件调用?
目前,我通过让我的 api 提供完整 URL 而不是相对路径来解决这个问题,但我不确定在处理静态文件时这是否是一种常见或良好的做法。
我在我的数据库中保存相对路径,并运行以下方法来生成 URL
public string GenerateUrl(string filePath, HttpRequest ctx) {
string physicalPath = this.GetRootPath() + filePath;
var url = physicalPath.Replace(Directory.GetCurrentDirectory (),$@"{ctx.Scheme}://{ctx.Host}").Replace(@"SystemData", @"Data");
return url;
}
谢谢。
【问题讨论】:
-
不确定我明白问题所在。为什么不简单地添加一个类似于代理配置的“/api”部分的部分,但使用“/Data”代替?
-
@JBNizet 用于静态文件?
-
您的浏览器不知道也不关心它在向给定 URL 发送请求时得到的内容是否来自静态文件、数据库或其他任何东西:它发送 HTTP 请求,然后返回HTTP 响应。
-
@JBNizet,请允许我换个说法,Angular webserver 的相对路径与后端 API 不同
-
我不明白你的意思。据我了解您的问题,您的后端服务器在 URL /Data/blablabla 提供文件,并且您希望这些文件由 ng serve 在 URL /Data/blablabla 提供。因此,您希望 ng serve 作为这些 URL 的代理,就像它作为 URL /api/blablabla 的代理一样。
标签: angular asp.net-core-webapi static-files