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. The site opens at the address, but the error in the console is Uncaught SyntaxError: Unexpected token '<'. And the site does not include 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); } );
You are sending the html file in a.js file to the browser. The Problem with the style is caused because you don't send the css file with. You could use ExpressJs to send the whole directory:
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
use express.js, it will be more convenient and easy to use.
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'));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.