Home > database >  How to submit a html and js from server via Vanilla NodeJS with no modules
How to submit a html and js from server via Vanilla NodeJS with no modules

Time:05-18

I know that better use expressJS, but I want to understand the core NodeJS API's. I want to create a simplest server without any modules. Everywhere we can find the code for server which send only html file:

const fs = require('fs')
const http = require('http')
const path =require('path')

const server = http.createServer((req,res)=>{
fs.readFile(path.join(__dirname,'index.html'),(err,data)=>{
        if (err){
            throw err
        }
        res.writeHead(200,{'Content-Type':'text/html'})
        res.end(data)
    })
}).listen(8080, () => {
    console.log('Server running on port 8080')
})
server.on('request', (req, resp) => {
    if(req.url === '/' && req.method === 'GET') {
        data=fs.readFileSync(__dirname   '/index.html')
        resp.writeHead(200, {
            'Content-Type': 'text/html',
        })
        return resp.end(data)
    }
}) 

If I try send the index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>
<body>
    <h1 id="text">Hello!</h1>
    <button id="change">Change</button>
<script src="index.js"></script>
</body>
</html>

script file index.js don't loading. The example of index.js:

const text=document.getElementById('text')
const change = document.getElementById('change')
const col1='rgb(255, 0, 0)'
const col2='rgb(0, 0, 0)'
change.addEventListener('click', () => {
    
    if (text.style.color===col1){
         text.style.color=col2
    }else{
         text.style.color=col1
    }
})

How can I send two file: index.html and index.js via pure Node.js? The similar question for ExpressJS: Node.js serve HTML, but can't load script files in served page, but there used Express, in this question I want to use pure node.js.

CodePudding user response:

I think you need another if statement in your server.on('request', ...). The current if statement only deal with index.html

You can try this, I haven't test the code yet, but logically it should work:

server.on('request', (req, resp) => {
    if(req.url === '/' && req.method === 'GET') {
        data=fs.readFileSync(__dirname   '/index.html')
        resp.writeHead(200, {
            'Content-Type': 'text/html',
        })
        return resp.end(data)
    }

    // add this code
    if(req.url === '/index.js' && req.method === 'GET'){
        data=fs.readFileSync(__dirname   '/index.js')
        resp.writeHead(200, {
            'Content-Type': 'application/javascript',
        })
        return resp.end(data)
    }
}) 
  • Related