Fırat Batar
Fırat Batar

Reputation: 13

How can i get response from another JavaScript file while working with nodejs and express?

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)

Upvotes: 1

Views: 861

Answers (1)

jfriend00
jfriend00

Reputation: 707308

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).

Upvotes: 1

Related Questions