简体   繁体   中英

nodejs can not include js file in EJS

i want to load a JS file into my EJS File but it doesnt find the JS File.

I use "app.use('/', express.static(path.join(__dirname, '/frontend')));" but it doesnt work.

Or is there a better way instead of include a js file to ejs file.

..............................

Folder Structur:

│
├──server.js
├──package-lock.json
├──package.json
│
├── js/
    ├── data.js
├── node_modules/
└── views/
    ├── index.ejs
    └── 404.ejs

server.js

'use strict';

const http = require('http');

const express = require('express');

const path = require('path');

const app = express();

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

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    const blogs = [
        { titel: 'Neuer Titel', desc: 'Data'},
        { titel: 'Titel 2', desc: 'New Desc'}
    ];
    res.render('index', {
        title: 'Home',
        blogs
    });
});

app.use('/*', (req, res) => {
    res.status(404).render('404');
});

app.listen(process.env.PORT || 3000, () => {
    console.log('Server listen');
});

Index.ejs

<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Data | <%= title %></title>
    </head>
    <body>

        <nav>
            <ul>
                <li>
                    <a href="/">Data</a>
                </li>
                <li>
                    <a href="/about">Data2</a>
                </li>
                <li>
                    <a href="/about/create">Data3</a>
                </li>
            </ul>
        </nav>
    </body>
    <script src="/frontend/data.js"></script>
</html>

I don't think it is possible to load a JS file in EJS but you can try to do so via a parient (folder)

Try to insert your script inside body tag

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