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
  • 623
  • 6
  • 20
  • You need to set up express to send static files. –  Jul 07 '21 at 07:13
  • 1
    Docs are your best friend: https://expressjs.com/en/starter/static-files.html – PsyGik Jul 07 '21 at 07:13
  • 2
    Duplicate: [static files with express.js](https://stackoverflow.com/questions/10434001/static-files-with-express-js) –  Jul 07 '21 at 07: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,535
  • 1
  • 27
  • 44