1

I am working on a node js app.

This is the code of the index.html file

<h1 id="h">hello</h1>
<script src="client.js"></script>

I am willing to change the innerHTML of that h1 to hai.

This my code in the client.js file

document.getElemntById("h").innerHTML = "hai";

I don't like using script tags in html

I have these codes in the server.js file(main file);

const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.sendFile(__dirname+"/index.html");
});

But, It is only sending the index.html.It is not sending the client.js. I also tried inserting multiple parameters.

const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.sendFile(__dirname+"/index.html",__dirname+"/client.js");
});

It is not still working.

What should I do?

I am new to programming, node, and StackOverflow.So please forgive me if there Are any problems

Musafiroon
  • 485
  • 1
  • 14

1 Answers1

1

res.sendFile & express.static both will work for this

var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');

// viewed at http://localhost:8080
app.get('/', function(req, res) {
    res.sendFile(path.join(public, 'index.html'));
});

app.use('/', express.static(public));

app.listen(8080);

Where your public directory will contain all *.css, *.js and other files

PsyGik
  • 3,222
  • 1
  • 25
  • 42