Home > Mobile >  [HTML][Express] app crashing when using npm start in terminal
[HTML][Express] app crashing when using npm start in terminal

Time:10-19

Below is my code and the package.json I have looked at similar questions but the error codes given were different than mine. What can I do to prevent crashing and get the app to run?

Should open a local site with a home page that allows navigation to a different site with a table that lists a few stocks and prices.

package.json

  "name": "assignment3",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "nodemon": "^2.0.12"
  }
}

my code


const PORT = 3000;

// The variable stocks has the same value as the variable stocks in the file 'stocks.js'
const stocks = require('./stocks.js').stocks;

const express = require("express");
const app = express();


app.use(express.urlencoded({
    extended: true
}));

app.use(express.static('public'));
// Note: Don't add or change anything above this line.

// Add your code here

app.get('/',function(req,res) {
    res.sendFile(path.join(__dirname '/index.html'));
    });

app.get('/listing', function(req, res){
    res.sendFile(path.join(__dirname  '/stocklist.html'))
     })

app.get('/sort', function(req, res){
    res.sendFile(path.join(__dirname  '/listingorder.html'))
     })

app.post('/placeorder', (req, res) => {
    console.log(req.body)
res.status(200).send("Placed")
})

app.get('/asc', function(req, res){
    let sorted = stocks.sort(function(a, b) {
        return parseFloat(a.price) - parseFloat(b.price);
    });
    res.status(200).send({stock: sorted})
 })

app.get('/dsc', function(req, res){
   let sorted = stocks.sort(function(a, b) {
       return parseFloat(b.price) - parseFloat(a.price);
   });
   res.status(200).send({stock: sorted})
})

app.get('/stocks', function(req, res) {
    //var data = {stock: stocks};
    res.status(200).send({stock: stocks});
})
app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}...`);
});


index.html

<!DOCTYPE html>

    <><head>

    </head><body>
            <p>Home Page</p>
            <a href="http://localhost:3000/listing">Stocks</a>

            <a href="http://localhost:3000/sort">Order by low high</a>

            <script>

            </script>

        </body><html>

            stocklist.html

            <html>


                <head>

                </head>

                <body>
                    <div>
                    </div>
                    <script>
                        function load(){fetch('http://localhost:3000/stocks')
                            .then(response => response.json())
                            .then(
                                (data) => {
                                    console.log(data);
                                    generate_table(data);
                                }
                            )};
                        }


                        function generate_table(data) {
                            // get the reference for the body
                        }
// get the reference for the body
                        var body = document.getElementsByTagName("div")[0];

// creates a <table> element and a <tbody> element
                            var tbl = document.createElement("table");
                            var tblBody = document.createElement("tbody");
                            var row = document.createElement("tr");
                            var cell = document.createElement("th");
                            var cellText = document.createTextNode("Company");
                            cell.appendChild(cellText);
                            row.appendChild(cell);
                            var cell = document.createElement("th");
                            var cellText = document.createTextNode("Price");
                            cell.appendChild(cellText);
                            row.appendChild(cell);
                            var cell = document.createElement("th");
                            var cellText = document.createTextNode("Symbol");
                            cell.appendChild(cellText);
                            row.appendChild(cell);
                            tblBody.appendChild(row);
                            // creating all cells
                            for (var i = 0; i <data.stock.length />; i  ) {
                                // creates a table row
                            }
// creates a table row
                            var row = document.createElement("tr");


                            var cell = document.createElement("td");
                            var cellText = document.createTextNode(data.stock[i].company);
                            cell.appendChild(cellText);
                            row.appendChild(cell);

                            var cell = document.createElement("td");
                            var cellText = document.createTextNode(data.stock[i].price);
                            cell.appendChild(cellText);
                            row.appendChild(cell);

                            var cell = document.createElement("td");
                            var cellText = document.createTextNode(data.stock[i].symbol);
                            cell.appendChild(cellText);
                            row.appendChild(cell);

                            // add the row to the end of the table body
                            tblBody.appendChild(row);
                            }

// put the <tbody> in the <table>
                                tbl.appendChild(tblBody);
// appends <table> into <body>
                                    body.appendChild(tbl);
                                    // sets the border attribute of tbl to 2;
                                    tbl.setAttribute("border", "2");
                                    }


                                    load();

                                    function postForm(ev){ev.preventDefault()};
                                    let body = {symbol}: document.getElementById("symbol").value,
                                    qty: document.getElementById("qty").value,
                                    }
                                    console.log(body);
                                    fetch("http://localhost:3000/placeorder", {
                                        // Adding method type
                                        method}: "POST",
                                    body:body,

                                    })

                                    .then(response => response.json())

                                    .then(json => console.log(json));
                                    }
                                </script>
                                    <br />
                                    <form onsubmit="postForm($event)">
                                        Symbol: <input type="text" id="symbol"></>
                                    </form>

                                    <br />
                                    <br />

                                </body>


                            </html>

                                listingorder.html

                                <html>


                                    <head>

                                    </head>

                                    <body>
                                        <div>
                                        </div>
                                        <script>
                                            function load(){fetch('http://localhost:3000/stocks')
                                                .then(response => response.json())
                                                .then(
                                                    (data) => {
                                                        console.log(data);
                                                        generate_table(data);
                                                    }
                                                )};
                                            }


                                            function generate_table(data) {
                                                // get the reference for the body
                                            }
// get the reference for the body
                                            var body = document.getElementsByTagName("div")[0];

// creates a <table> element and a <tbody> element
                                                var tbl = document.createElement("table");
                                                var tblBody = document.createElement("tbody");
                                                var row = document.createElement("tr");
                                                var cell = document.createElement("th");
                                                var cellText = document.createTextNode("Company");
                                                cell.appendChild(cellText);
                                                row.appendChild(cell);
                                                var cell = document.createElement("th");
                                                var cellText = document.createTextNode("Price");
                                                cell.appendChild(cellText);
                                                row.appendChild(cell);
                                                var cell = document.createElement("th");
                                                var cellText = document.createTextNode("Symbol");
                                                cell.appendChild(cellText);
                                                row.appendChild(cell);
                                                tblBody.appendChild(row);
                                                // creating all cells
                                                for (var i = 0; i <data.stock.length />; i  ) {
                                                    // creates a table row
                                                }
// creates a table row
                                                var row = document.createElement("tr");


                                                var cell = document.createElement("td");
                                                var cellText = document.createTextNode(data.stock[i].company);
                                                cell.appendChild(cellText);
                                                row.appendChild(cell);

                                                var cell = document.createElement("td");
                                                var cellText = document.createTextNode(data.stock[i].price);
                                                cell.appendChild(cellText);
                                                row.appendChild(cell);

                                                var cell = document.createElement("td");
                                                var cellText = document.createTextNode(data.stock[i].symbol);
                                                cell.appendChild(cellText);
                                                row.appendChild(cell);

                                                // add the row to the end of the table body
                                                tblBody.appendChild(row);
                                                }

// put the <tbody> in the <table>
                                                    tbl.appendChild(tblBody);
// appends <table> into <body>
                                                        body.appendChild(tbl);
                                                        // sets the border attribute of tbl to 2;
                                                        tbl.setAttribute("border", "2");
                                                        }


                                                        load();

                                                        function postForm(ev){ev.preventDefault()};
                                                        let body = {symbol}: document.getElementById("symbol").value,
                                                        qty: document.getElementById("qty").value,
                                                        }
                                                        console.log(body);
                                                        fetch("http://localhost:3000/placeorder", {
                                                            // Adding method type
                                                            method}: "POST",
                                                        body:body,

                                                        })

                                                        .then(response => response.json())

                                                        .then(json => console.log(json));
                                                        }
                                                    </script>
                                                        <br />
                                                        <form onsubmit="postForm($event)">
                                                            Symbol: <input type="text" id="symbol"></>
                                                        </form>

                                                        <br />
                                                        <br />

                                                    </body>
function StocksByPrice(){
    if (Number(x.table) > Number(y.table)) {
        shouldSwitch = true;
        break;
}
}
                                                </html>


// Note: Don't add or change anything below this line.
app.listen(PORT, () => {console.log(`Server listening on port ${PORT}...`)};
});

When running npm start I get this error

> assignment3@1.0.0 start D:\Comp Sci\CS 290 Web Development\Assignment 3
> nodemon server.js

[nodemon] 2.0.13
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
D:\Comp Sci\CS 290 Web Development\Assignment 3\server.js:63
<!DOCTYPE html>
          ^^^^
SyntaxError: Unexpected identifier
    at wrapSafe (internal/modules/cjs/loader.js:988:16)
    at Module._compile (internal/modules/cjs/loader.js:1036:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...

CodePudding user response:

I would try and create a 'view' folder and render pages from there. Did you try that?

CodePudding user response:

**Sample of the server.js file **

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

// App constants
const PORT = 3000
const app = express();
// App middlewares
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ extended: true }));
// Static folder
app.use(express.static(path.resolve(__dirname, "public")));
// app.set("views", path.resolve(__dirname, "./views/"));

// App routes
app.get("/", (req, res) => {
  return res.sendFile(path.join(__dirname,"/views/index.html"))
})
// App server
app.listen(PORT, () => {
  const message = `Server running on http://localhost:${PORT}`;
  console.log(message);
});

In your root directory create a views directory, import the path module in your server file. Create a folder named views add your index.html inside the views directory and send files as I have shown in the code snippet shown above. The views folder will hold all your HTML files so that you don't mix HTML files with javascript files. Alternatively, you can check out some templating engines like pug, ejs, or handlebars for writing your views

My directory structure

Directory structure

  • Related