Home > Mobile >  How to run index.html on Node.JS
How to run index.html on Node.JS

Time:08-11

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);
  }
);

Error:enter image description here

enter image description here

CodePudding user response:

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

CodePudding user response:

if it's a HTML page it must end with .html not .js, change the extension of the file

CodePudding user response:

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'));
});
  • Related