简体   繁体   中英

How to serve script file from Express route

I have a js script that I want to include in src attribute in my html file. When I am directly adding script from local path, it is working.

Is it possible to return file path from an express route and use the route as value of src in my html? This is how I want to include my express route in html

<script src="http://localhost:2222/widget" type="text/javascript"></script>

Express server is running on port 2222 and has some apis. Now in my express route /widget

app.get("/widget", (req, res) => {
     res.send(path.join(__dirname + "/src/client/public/bundle.js"));
});

When I simply trigger localhost:2222/widget a correct path shows up starting from /home/...

I need some machanism to use this js file path as src (as shown above).

Note: I have added all cors, headers etc. for access control.

Use res.sendFile() to send the file instead of the path:

Transfers the file at the given path . Sets the Content-Type response HTTP header field based on the filename's extension. Unless the root option is set in the options object, path must be an absolute path to the file.

So, your code becomes:

app.get("/widget", (req, res) => {
     res.sendFile(path.join(__dirname, "/src/client/public/bundle.js"), err => console.log(err));
});

Since you are using path.join() you can separate __dirname and the relative path by a comma.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM