簡體   English   中英

Node.js 從終端運行應用程序一切正常,但是當應用程序通過 npm“啟動”腳本啟動時,它僅加載 html 而沒有公共文件夾中的所有 static 文件

[英]Node.js run app from terminal all work fine but when app start by npm "start" script it load only html without all static files in public folder

我有一個簡單的 web 站點,它使用 node.js 和 express.js 當我使用命令“node app.js”或“nodemon app.js”從終端啟動我的 app.js 文件時,它工作正常。 它加載我所有的 static 文件,如 css 和公共文件夾中的圖像。 但是,當我運行 npm 啟動腳本時,它會運行但不會加載我的 static 文件,例如圖像和 css 文件,只有 html 文件沒有應用我的 css 類並且不顯示圖像。 我需要解決這個問題,因為我想將我的網站部署到 heroku 但 heroku 運行應用程序使用 package.json 的啟動腳本

我的 html 文檔的一部分,我鏈接 css 文件並使用圖像

 <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <:-- Load Google Fonts --> <link rel="preconnect" href="https.//fonts.googleapis:com"> <link rel="preconnect" href="https.//fonts.gstatic:com" crossorigin> <link href="https.//fonts.googleapis?com/css2:family=Nunito+Sans;wght@400;600:700&family=Poppins;wght@400;500;600.700&display=swap" rel="stylesheet"> <.-- Load styles.css file --> <link rel="stylesheet" href="/css/styles.css"> <title>Online Learning</title> </head> <body> <div class="wrapper"> <header class="section-header"> <div class="base-container header-container top-nav" id="myTopNav"> <div class="logo"> <img src="/images/polygon.png" alt="polygon" class="polygon"> <img src="/images/skilline.png" alt="brand-name" class="brand-name"> </div>

和我的 app.js 文件

 const express = require('express'); const app = express(); const path = require('path'); app.use(express.static("public")); app.get("/", (req, res) => { res.sendFile(path.join(__dirname, '/index.html')); }); app.listen(process.env.PORT || 3000, function () { let date = new Date(Date.now()); let serverStartTime = date.getDate() + "." + date.getMonth() + "." + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); console.log("Server was start/restart on port 3000: " + serverStartTime); });

我的 package.json 文件

 { "name": "online-learning-landing-page", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "node src/app.js", "start": "npm run dev" }, "repository": { "type": "git", "url": "git+https://github.com/grigore994/Online-Learning-Landing-Page.git" }, "author": "", "license": "ISC", "bugs": { "url": "https://github.com/grigore994/Online-Learning-Landing-Page/issues" }, "homepage": "https://github.com/grigore994/Online-Learning-Landing-Page#readme", "dependencies": { "express": "^4.17.3", "path": "^0.12.7" } }

和我的項目結構

在此處輸入圖像描述

當我從終端運行“node app.js”時的結果在此處輸入圖像描述

當我運行 npm 啟動腳本時的結果

在此處輸入圖像描述

不要將 app.js 放在 public 中,這很危險,不推薦。 將它移到上面一個目錄,與您的 package.json 同一級別

然后將此行更改為“dev”:“node app.js”,

暫無
暫無

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

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