简体   繁体   中英

my javascript file not linking? Iam using: app.use(express.static(__dirname + '/public'));

my file structure:

  • project
    • public
      • javascripts
        • char1.js
    • views
      • home.ejs
    • app.js

I store my ejs in a subfolder, i want to access chart1.js file which is in another subfolder,

i using app.use(express.static(__dirname + '/public')); middleware. i have been stuck in this error for hours: thanks for helping!!!!

homes.ejs file

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Inconsolata:wght@300&display=swap" rel="stylesheet">
    <title>Home</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"
        integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.js"></script>
    <link rel="stylesheet" href="/stylesheets/app.css">
</head>
<body class=" ">
    <div id="chart1"></div>
         <button id="refresh2">Refresh this chart</button>
         <script src="/javascripts/chart1.js"></script>
    </div>
</body>

</html>

chart1.js file:

import ChartsEmbedSDK from '@mongodb-js/charts-embed-dom';
const sdk = new ChartsEmbedSDK({
    baseUrl: 'https://charts.mongodb.com/charts-project-0-qumgu'
});

const chart = sdk.createChart({
    chartId: '1e32b53f-6de2-45d2-863d-025b85c8bec9',
    weidth: 100,
    height: 100,
});
chart.render(document.getElementById('chart1'))

app.js file:

if (process.env.NODE_ENV !== "production") {
require('dotenv').config();
}

const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const Data = require('./models/data');

const dbUrl = process.env.DB_URL || 'mongodb://localhost:27017/predict-football';
mongoose.connect(dbUrl, {
    useNewUrlParser: true,
    useUnifiedTopology: true,


});

const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
    console.log("database connected")
})

const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(express.urlencoded({ extended: true }))
app.use(express.static(__dirname + '/public'));


app.get('/home', async (req, res) => {
    const datas = await Data.find({}).sort({ _id: -1 });
    console.log(datas.length)
    res.render('home', { datas })

})
app.post('/home', async (req, res) => {
    const data = new Data(req.body.data);
    console.log(data)
    await data.save();
    res.redirect('/home')
})

    if (process.env.NODE_ENV !== "production") {
    require('dotenv').config();
}

const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const Data = require('./models/data');

const dbUrl = process.env.DB_URL || 'mongodb://localhost:27017/predict-football';
mongoose.connect(dbUrl, {
    useNewUrlParser: true,
    useUnifiedTopology: true,


});

const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
    console.log("database connected")
})

const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(express.urlencoded({ extended: true }))
app.use(express.static(__dirname + '/public'));


app.get('/home', async (req, res) => {
    const datas = await Data.find({}).sort({ _id: -1 });
    console.log(datas.length)
    res.render('home', { datas })

})
app.post('/home', async (req, res) => {
    const data = new Data(req.body.data);
    console.log(data)
    await data.save();
    res.redirect('/home')
})

app.all('*', (req, res, nwxt) => {
    res.send("404!!!")
})

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`serving on port ${port}`)
})

app.all('*', (req, res, nwxt) => {
    res.send("404!!!")
})

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`serving on port ${port}`)
})

You have to replace:

app.use(express.static(__dirname + '/public'));

To:

app.use(express.static('public'))

And to get chart1.js

Insted of this:

<script src="../public/javascripts/chart1.js"></script>

Use this:

<script src="/javascripts/chart1.js"></script>

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