[英]Express.js HTTP 500 ERROR: Page works with res.send(“Some text”); but does error caused when using res.render('file');
[英]HTML page does not render properly when using express.js
我正在測試使用express.js顯示主頁(index.html頁面)。 當我直接從瀏覽器加載時,此索引頁可以完美加載/呈現在瀏覽器上。 但是,當我嘗試通過express.js加載同一頁面時,不會得到相同的效果。 它僅以CSS樣式逐行顯示所有元素和圖片。 誰能讓我知道丟失了什么? 我正在加載的索引頁來自模板。 以下是帶有路由的getwebapp.js文件。 我只顯示到索引頁面的路線。
getwebapp.js內容:
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
app.use(express.static(path.join(__dirname + 'public')));
router.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));});
router.get('/about", function (req, res) {
res.sendFile(path.join(__dirname + '/about.html'));});
app.use('/', router);
app.listen(8080, () => console.log('Listening on port 8080....'));
console.log('Server started at ' + Date());
index.html內容(上半部分)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello World</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Swiper CSS -->
<link rel="stylesheet" href="css/swiper.min.css">
<!-- Styles -->
<link rel="stylesheet" href="style.css">
<script src="js/custom.js"></script>
</head>
<body>
<header class="site-header">
<div class="nav-bar">
<div class="container">
<div class="row">
<div class="col-12 d-flex flex-wrap justify-content-between align-items-center">
<div class="site-branding d-flex align-items-center">
<a class="d-block" href="index.html" rel="home"><img class="d-block" src="images/logo.png" alt="logo"></a>
</div><!-- .site-branding -->
<nav class="site-navigation d-flex justify-content-end align-items-center">
<ul class="d-flex flex-column flex-lg-row justify-content-lg-end align-items-center">
<li class="current-menu-item"><a href="/">Home</a></li>
<li><a href="/about">About us</a></li>
<li><a href="/services">Services</a></li>
<li><a href="/news">News</a></li>
<li><a href="/contact">Contact</a></li>
<li class="call-btn button gradient-bg mt-3 mt-md-0">
<a class="d-flex justify-content-center align-items-center" href="#"><img src="images/emergency-call.png"> +34 586 778 8892</a>
</li>
</ul>
</nav><!-- .site-navigation -->
您不能直接使用節點js(表示js)呈現html頁面。 使用express.static 。 我已經從該網站上閱讀了如何使用express js渲染html頁面
希望這可以幫到你
嘗試將標題設置為html
app.get("/", function(req, res) {
res.type('html');
res.sendFile(path.join(__dirname, "index.html"));
});
如果那不起作用,請嘗試 :
app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/files')); app.use(express.static(__dirname + '/uploads'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.