1

I'm trying to learn nodejs and express and i created a simple server. I want to run some JS code for response.

When I used this method it's works.

const express = require('express');
const path = require('path');
require('dotenv').config();


const app = express();
const port = process.env.PORT || "8000";



app.get('/', (req, res) => {
    res.send(`<script>
    console.log("Program works!");
    </script>`);
});



app.listen(port, () => {
    console.log(`Listening to requests on http://localhost:${port}`);
});

But writing JS as String is hard so I tried this:

const express = require('express');
const path = require('path');
require('dotenv').config();


const app = express();
const port = process.env.PORT || "8000";



app.get('/', (req, res) => {
    res.send(`<script src="./response.js"></script>`);
});



app.listen(port, () => {
    console.log(`Listening to requests on http://localhost:${port}`);
});

And i get this error:

GET http://localhost:8000/response.js net::ERR_ABORTED 404 (Not Found)

1
  • In client you won't have access to the server assets directly till you bundle them together or in a place where client can also access it (usually at the same location where you place your css and images). The right way though would be to push them to a CDN where you can access it from anywhere Commented Aug 21, 2021 at 5:38

1 Answer 1

1

When you send this:

<script src="./response.js"></script>

to the browser, the browser will parse that and see the src attribute and will then immediately request ./response.js from your server. But your server doesn't have any route to respond to that request (thus it gets a 404 error back from your server). Remember that a nodejs server serves NO files by default (unlike some other web servers). So, you have to create routes or middleware for anything that you want it to serve.

So, you need to add a route to your server that will response to a request for response.js. First change your <script> tag to this:

<script src="/response.js"></script>

You want the request to be "path absolute" so it does not depend upon the path of the containing page. Then, you need to add a route handler for response.js to your server.

This can be done as a single route:

app.get('/response.js', (req, res) => {
    res.sendFile("response.js", {root: __dirname});
});

Or, you can use express.static() to serve a whole directory of publicly available files with one line of code (if you also move all publicly available static files to their own directory away from your server files).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.