下面是我的代碼和 package.json 我看過類似的問題,但給出的錯誤代碼與我的不同。我該怎么做才能防止崩潰并使應用程式運行?
應該打開一個帶有主頁的本地站點,該主頁允許導航到帶有列出一些股票和價格的表格的不同站點。
包.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"
}
}
我的代碼
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}...`)};
});
運行 npm start 時出現此錯誤
> 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...
uj5u.com熱心網友回復:
我會嘗試創建一個“視圖”檔案夾并從那里渲染頁面。你試過嗎?
uj5u.com熱心網友回復:
**server.js檔案樣本**
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);
});
在您的根目錄中創建一個視圖目錄,path在您的服務器檔案中匯入模塊。在目錄中創建一個名為viewsadd your的檔案夾并發送檔案,如我在上面顯示的代碼片段中所示。該檔案夾將保存您所有的 HTML 檔案,這樣您就不會將 HTML 檔案與 javascript 檔案混合在一起。或者,你可以檢查出一些模板引擎一樣,或寫你的意見index.htmlviewsviewspugejshandlebars
我的目錄結構
![[HTML][Express] 在終端中使用 npm start 時應用程式崩潰](https://img.uj5u.com/2021/10/21/3f28b940a8c5485195979a4d56afd9fa.png)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/328774.html
