簡體   English   中英

如何使用 Angular 10 img 標簽中的絕對路徑在 nodejs 服務器中提供靜態圖像?

[英]How to serve static images in nodejs server using absolute path in Angular 10 img tag?

我一直在這里搜索並沒有找到解決方案,所以我在問。 如何提供位於 nodejs 服務器中的靜態圖像:

public/img

Nodejs(在 app.listen() 之前):

app.use("/api", routesIndex);
app.use(express.static(__dirname + '/public/img'));

Angular 10 模板:

<img class="center" [src]="quizService.rootUrl+'/public/img/'+quizService.questions[quizService.questionProgress].imageName+'.jpg'">

[src] 解析為絕對正確的路徑:

http://localhost:5000/api/public/img/shark.jpg

但它仍然顯示404。 有任何想法嗎?

謝謝

無需添加靜態服務目錄的路徑。 只需刪除'/public/img/'

<img class="center" [src]="quizService.rootUrl + quizService.questions[quizService.questionProgress].imageName+'.jpg'">

您可以直接訪問服務目錄的所有文件。 喜歡:

http://localhost:5000/shark.jpg

按照以下步驟,

your image is at path Public/img/shark.jpg

在你的 app.js 中,這應該在創建任何路由之前

app.use(express.static(__dirname + '/public/img'));

創建如下路線

app.get('/Image/:id', function (req, res) {
    // logic to find image based on id passed, we will assume it results in shark.jpg
    const filepath = `${__dirname}/public/img/shark.jpg`;
    res.sendFile(filepath);
});

現在從你的角度代碼使用這個端點

localhost:{PORT_NUMBER}/Image/{ID_FOR_SHARK_IMAGE}

我通過執行以下操作使其工作:

Nodejs添加路徑:

const path = require("path");

app.use(express.static(path.join(__dirname, 'public/img')));

然后在 Angular 中創建了一個單獨的 assetUrl,它省略了 baseUrl 的“/api”部分:

[src]="quizService.assetUrl+'/'+quizService.questions[quizService.questionProgress].imageName+'.jpg'"

現在我的圖像已送達。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM