Adding local script files to EJS views

2020-08-01 16:32发布

问题:

I've got a Node/Express/EJS app. It's got a folder for views and another for client files. The latter has another folder for javascript, where I have a file called frontend.js.

I'd like to load jQuery and the frontend.js file in this view.

The standard script tags don't work.

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="../client/js/frontend.js"></script>

jQuery loads, frontend.js throws a 404 error.

Is there a special way of doing this that I'm not aware of?

回答1:

in your app.js file add this :

app.use(express.static(path.join(__dirname, 'client')))

change the second script tag to :

<script type="text/javascript" src="/js/frontend.js"></script>

I'm assuming that your app.js file and client folder are in the same folder.