html - [HTML][Express] 在终端中使用 npm start 时应用程序崩溃
问题描述
下面是我的代码和我查看过类似问题的 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...
解决方案
**文件样本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
模块导入您的服务器文件中。在目录中创建一个名为views
add your的文件夹并发送文件,如我在上面显示的代码片段中所示。该文件夹将保存您的所有 HTML 文件,这样您就不会将 HTML 文件与 javascript 文件混合在一起。或者,您可以查看一些模板引擎,例如,或用于编写您的视图index.html
views
views
pug
ejs
handlebars
我的目录结构
推荐阅读
- php - 如何从 Wordpress 解析 XML 文件以在另一个 CMS 中使用?
- python - if条件python pandas的索引计数器
- javascript - 使用数组内的值查找对象键?
- oracle - 使用连接更新 Oracle 中的语句
- drupal - Drupal:向类别添加了新的分类术语,但与不同类别一起使用时会引发错误
- android - 单击时汉堡菜单没有响应
- mysql - MySQL 不等于某个长度
- reactjs - 如何在样式化组件中使用类
- java - 如何从 ScheduledFuture 任务中获取委托
- php - 如何在jquery中将字符串添加到选项菜单X次