0

I am trying to connect my html code with my node JS server , but when I try to run the server only html is rendered . What should be the solution for this , also should I put my all html files in views folder ??? Here is my node JS code :

const http = require('http');
const fs = require('fs')
const express = require('express')
const bodyParser = require('body-parser');
const app = express()


app.use(bodyParser.json())
app.use("/static", express.static('./Frontend/Project/assets'));

const FronteEndserver = http.createServer((req,res) => {
    const path = new URL(req.url , 'http://localhost:8000').pathname 
    if(path == '/')
    {
        fs.readFile('./Frontend/Project/index.html' , function(error , data) {
            if(error)
            {
                res.writeHead(404)
                res.write(error , (err) => {
                return res.end()
                })
            }
            else{
                res.writeHead(200 , {
                    'Content-Type': 'text/html'
                })
                console.log("Frontend Server");
                res.write(data , (err) => {
                return res.end()
                })
            }
        })
    }
    else if(path == '/docs')
    {
        fs.readFile('./Frontend/Project/docs.html' , function(error ,data) {
            if (error) {  
                res.writeHead(404);  
                res.write(error , (err) => {
                return res.end()
                })  
            }
            else{
                res.writeHead(200 , {
                    'Content-Type': 'text/html'
                })
                res.write(data , (err) => {
                return res.end()
                })
            }
        })
    }
    else{
        res.writeHead(404)
        res.write("Oops this doesn't exist - 404")
        return res.end();
    }
} , app).listen(8000)

Here is my index.html file where I imported the node JS script -->

<script type = "text/javascript" src = "../../server.js"></script>

This is how my project directory looks :

 -Frontend                                                             
  -Project
   -assets(which contains my static folders)
    -CSS_folder
    -JS_folder
    -Img_Folder 

-server.js
  
  • Are you looking for [this answer](https://stackoverflow.com/questions/35995273/how-to-run-html-file-using-node-js)? – Sato Takeru Feb 19 '22 at 14:26
  • 1
    You are trying pass two separate request listeners to `http.createServer()`. I don't see anywhere in the doc where that is supported. If you're going to use Express, then use it for all your request handlers - don't try to mix and match plain http listeners with express listeners. – jfriend00 Feb 19 '22 at 15:11
  • @jfriend00 what should I change in my code and also why my static files are not rendering . –  Feb 19 '22 at 16:48

0 Answers0