Search code examples
javascriptexpresschart.jshttp-status-code-404ejs

404 Not Found Error when trying to display a chart with Chart.js


I am using ejs and express to render my page. What I am trying to do is display a chart on my website using Chart.js. On the website, I don't see the chart. In the terminal window, I don't see any error. But when I open up the console in Google Chrome, I see a 404 Not Found error.


File structure:

My file structure


Code:

app.js

// Imports
const express = require("express");
const fetch = require("node-fetch");

// Setting up Express and EJS
const app = express();

app.set('view engine', 'ejs');
app.use(express.static('Public'));
app.get('/',function (req, res) {
    getData().then(home => {
        res.render('index', {all_prices, all_percents, all_differences, stocks, companies});
    }).catch(err => {
        console.log(err);
        res.sendStatus(500);
    });
});
app.listen(3000);

// Round function
function Round(number) {
    return Math.round(100*number)/100;
}

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

const start_unix = new Date(yyyy + "." + mm + "." + dd).getTime() / 1000

const current_unix = Math.floor(Date.now() / 1000)

// Links to the APIs
const companies = ["Apple", "Tesla", "Zoom", "Cognizant", "General Motors", "IBM"];
const stocks = ["AAPL", "TSLA", "ZM", "CTSH", "GM", "IBM"];

var real_time = [];
var candle_position = [];

for (let i = 0; i < stocks.length; i++) {
    real_time.push("https://finnhub.io/api/v1/quote?symbol=" + stocks[i] + "&token=[API KEY]");
    candle_position.push("https://finnhub.io/api/v1/stock/candle?symbol=" + stocks[i] + "&resolution=1&from=" + start_unix + "&to="+ current_unix +"&token=[API KEY]");
}

// Retrieving Data from the API
var all_prices = [];
var all_percents = [];
var all_differences = [];
var all_historical_price = [];

async function getData() {
    for (i = 0; i < real_time.length; i++){
        const real_time_res = await fetch(real_time[i]);
        const candle_position_res = await fetch(candle_position[i]);
        const real_time_data = await real_time_res.json();
        const candle_position_data = await candle_position_res.json();

        const price = Round(real_time_data.c);
        const open_price = real_time_data.o;
        const historical_price = candle_position_data.c;

        const difference = Round(price - open_price);
        const percent = Round((difference/open_price) * 100);

        all_prices.push(price);
        all_percents.push(percent);
        all_differences.push(difference);
        all_historical_price.push(historical_price);
    }
}

module.exports.all_historical_price = "all_historical_price";

plotting_chart.js

const app = require("/Users/sarasimon/Documents/Programs/Stock Market Website/app");

var ctx = document.getElementById('chart').getContext('2d');

for (i = 0; i < app.all_historical_price.length; i++) {
    var chart = new Chart(ctx, {
        type: 'line',
        data: {
            datasets: [{
                label: '# of Votes',
                data: app.all_historical_price[i],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: false
                    }
                }]
            }
        }
    });
}

index.ejs

<!DOCTYPE html>
<html>
    <head>

        <title>Stock Charts</title>

        <!-- Favicon -->
        <link rel="icon" type="image/png" href="Images/favicon.png"/>

        <!-- CSS -->
        <link rel="stylesheet" href="styles.css">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
        <link rel="preconnect" href="https://fonts.gstatic.com"> 
        <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@300&display=swap" rel="stylesheet">

    </head>
    <body>

        <!-- Title Bar -->
        <div id="title_bar">
            <img class="logo" src="Images/Logo.png">
            <h1>Stock Charts</h1>
        </div>

        <!-- Stocks -->
        <div id="stocks">
            <div class="row">

                <% for (let i = 0; i < stocks.length; i++) { %>

                <div class="col-sm-3">
                    <div class="card">
                        <canvas class="card-img-top" id="chart" height="250px"></canvas>
                        <div class="card-body">
                            <h5 class="card-title"><%= companies[i] %> (<%= stocks[i] %>)</h5>
                            <div class="card-text">
                                <p>Price: $<%= all_prices[i] %></p>
                                <p>Percent Change: <%= all_percents[i] %>%</p>
                                <p>Amount Change: <%= all_differences[i] %></p>
                            </div>
                        </div>
                    </div>
                </div>

                <% } %>

            </div>     
        </div>

        <!-- Javascript Links -->
        <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
        <script src="../plotting_chart.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.6.0/dist/umd/popper.min.js" integrity="sha384-KsvD1yqQ1/1+IA7gi3P0tyJcT3vR+NdBTt13hSJ2lnve8agRGXTTyNaBYmCR/Nwi" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.min.js" integrity="sha384-nsg8ua9HAw1y0W1btsyWgBklPnCUAFLuTMS2G72MMONqmOymq585AcH49TLBQObG" crossorigin="anonymous"></script>

    </body>
</html>

Output: This is the chrome page.


Solution

  • You can't call a file outside your public folder or a dir you set express to read. \n so first move it to the public folder and change <script src="../plotting_chart.js"></script> to <script src="./plotting_chart.js"></script>

    If this answers the question close the question as solve