简体   繁体   English

如何在 Node.JS 上运行 index.html

[英]How to run index.html on Node.JS

I need to run a website on a server.我需要在服务器上运行一个网站。 I installed Node.JS and created a server.js file in the project folder and read the index.html file there.我安装了 Node.JS 并在项目文件夹中创建了一个 server.js 文件,并在那里读取了 index.html 文件。 The site opens at the address, but the error in the console is Uncaught SyntaxError: Unexpected token '<'.该站点在该地址打开,但控制台中的错误是 Uncaught SyntaxError: Unexpected token '<'。 And the site does not include styles.并且本站不包括styles。 How can this problem be solved?如何解决这个问题?

 // server.js var http = require("http"); var fs = require("fs"); const PORT = 8080; fs.readFile( "../index.html", function (err, html) { if (err) throw err; http.createServer(function (request, response) { response.writeHeader(200, { "Content-Type": "text/html" }); response.write(html); response.end(); }).listen(PORT); } );

Error:错误: 在此处输入图像描述

在此处输入图像描述

You are sending the html file in a.js file to the browser.您正在将 a.js 文件中的 html 文件发送到浏览器。 The Problem with the style is caused because you don't send the css file with.样式问题是因为您没有发送 css 文件。 You could use ExpressJs to send the whole directory:您可以使用 ExpressJs 发送整个目录:

https://www.digitalocean.com/community/tutorials/nodejs-serving-static-files-in-express https://www.digitalocean.com/community/tutorials/nodejs-serving-static-files-in-express

if it's a HTML page it must end with.html not.js, change the extension of the file如果它是 HTML 页面,它必须以.html not.js 结尾,更改文件的扩展名

use express.js, it will be more convenient and easy to use.使用express.js,它会更方便易用。

const path = require('path');
const express = require('express');
const app = express();
    
app.use((req, res, next) => {
    res.status(404).sendFile(path.join(__dirname, 'views', '404.html'));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM