简体   繁体   中英

Node.js and Express: How to add script file to ejs file

This is my first time working with node.js and Express. I have the following project structure:

Project/
|-- app/
|   |-- script.js
|
|-- public/
|   |-- css/
|       |-- style.css
|   |
|   |-- resources/
|
|-- views/
|   |-- index.ejs
|
|-- app.js
|-- package.json
|-- package-lock.json

Now:

  • app.js -> starts the server
  • index.ejs -> contains the html code
  • style.css -> has the styling
  • script.js -> contains the front end functionality of my application

Before creating the server so that my application is run from there, the script file was simply included in the index.html (now the index.ejs) as usual, and everything worked fine. But now just including the script file in the ejs is not enough. In fact, the page just loads on the server but nothing functions.

I have tried adding the following in my script.js file as I found something on here, but it didn't work:

const express = require("express");
path = require('path');

const script = express();
script.use(express.static(path.join('../views', 'index')));

What do I have to do to link my script.js file with node.js and express, without having to develop a RESTful application ?

You're using express.static wrong.

Firstly, you really, really don't want to expose your ejs file for others to download. Doing so allows people to see the source code of your server (even if it's only the template) giving them more info to reverse-engineer your app. So remove this:

script.use(express.static(path.join('../views', 'index')));

Secondly you want people to be able to download your frontend scripts, css and images. To allow this (which is the direct answer to your question) you need to use express.static :

script.use(express.static(path.join('../app')));
script.use(express.static(path.join('../public')));

Once you have set this up you can simply include your frontend script the usual way in your ejs file:

<script src="/script.js">

The browser will do the rest for you.


Additional answer:

If you want your script to be served from the /app path instead of / you can set the path in Express:

script.use('/app', express.static(path.join('../app')));

Which can then be used as:

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

You need to tell express that use are using ejs


// set view engine to ejs
script.set("view engine", "ejs");
// you need to specify views folder too because your script.js is not in // root folder.
app.set('views','../views');
// serve public folder so you can include .css .js in your .ejs file.
app.use("/public", express.static("../public"));

//render you index file
app.use("/", (req,res)=>{
 return res.render("index");
});


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