我遇到了一些自定義路由代碼的問題,它一切正常并且與我所做的客戶端視圖路由同步,但是一旦我有一個子頁面,它就不會正確路由我的靜態檔案。
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
它不會從根目錄給我一個檔案,而是將它當作來自子檔案夾的檔案來提供。
示例:我轉到 http://localhost/sign-up,并加載了從/scripts加載到我的索引檔案中的檔案,但是如果我轉到 http://localhost/sign-up/2,它會嘗試從/sign-up/scripts加載腳本
const express = require('express');
const path = require('path');
const app = express();
app.use('/views', express.static(path.resolve(__dirname, 'frontend', 'views')));
app.use('/styles', express.static(path.resolve(__dirname, 'frontend', 'styles')));
app.use('/scripts', express.static(path.resolve(__dirname, 'frontend', 'scripts')));
app.use('/media', express.static(path.resolve(__dirname, 'frontend', 'media')));
app.get('/*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'frontend', 'newSite.html'));
});
app.listen(process.env.PORT || 1234, () => console.log('Server is now running...'));
為了解決這個問題,我一直在關注 DCODE 在 youtube 上的這些教程,但我看不出有什么不妥:
https://www.youtube.com/watch?v=6BozpmSjk-Y
https://youtu.be/OstALBk-jTc
uj5u.com熱心網友回復:
加載在注冊檔案夾中的資源應使用以“ /”字符開頭的 URL ,以使它們相對于站點根目錄,例如
src="/scripts/modulefile.js"
href="/css/stylesheet.css"
href="/media/image.png"
而不是相對于注冊檔案夾的 url - 如果'/'省略前導,它們將是。
uj5u.com熱心網友回復:
您不需要多個路由來為您的靜態內容提供服務,并且為您執行此類任務的static方法是express:
// If your 'public' or 'static' directory is one of root directories
app.use(express.static(process.cwd() '/public'));
// so all these requests will be served:
// -> /public/styles/custom.css
// -> /public/scripts/pollyfils.js
// -> /public/media/logo.png
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390743.html
標籤:javascript 节点.js 表达 单页应用程序 网址路由
上一篇:敵人的精靈不會向左翻轉
