javascript - 无法获取/nodeJS 问题,为什么我会收到此消息?
问题描述
请帮忙 - 我正在进入Cannot Get /
我的 NodeJS 应用程序。为什么我会收到此消息?我知道它在这里,抱歉,但我不知道为什么我会收到这条消息。我尽我所能尝试了一切,但我仍然没有得到它。
……………………………………………………………………………………………… .. ......
index.js
var express=require('express');
var filePersonData = require("fs")
var jsonData=require('./persons.json');
var parser = require("body-parser");
var jsonFile = "./persons.json"
var app=express();
app.use(parser.urlencoded({extended:true}));
app.use(parser.json());
app.use(express.static("./web"));
// WRITE TO FILE
function readPerson(){
var file = filePersonData.readFileSync(jsonFile, "utf-8");
var jsonDATA = JSON.parse(file);
return jsonDATA;
}
// WRITE NEW PERSON TO FILE
function addPerson(person){
var jsonDATA = readPerson();
jsonDATA.persons.push(person);
filePersonData.writeFileSync(jsonFile, JSON.stringify(jsonDATA));
}
// CHECK IF PERSON EXIST
function ifExist(newPerson){
var jsonDATA = readPerson();
for(var person of jsonDATA.persons){
if(person.name.toLowerCase() == newPerson.name.toLowerCase())
return true;
}
return false;
}
// post to web
app.post("/api/newPerson", function(request, response) {
var person =request.body;
if(ifExist(person)){
response.status(400);
}else{
response.status(201);
addPerson(person);
}
response.send();
});
app.get('/api/persons',(req,res)=>{
res.status(200);
var jsonDATA = readPerson();
res.send(JSON.stringify(jsonDATA));
});
// listening to port 3500
app.listen(3500,
()=>{console.log("Server is listening to port 3500")});
表单.html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
input[type=text],
select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.center {
margin: auto;
width: 60%;
border: 3px solid #73AD21;
padding: 10px;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
</style>
<script>
function loadData() {
let optionList = document.getElementById('country').options;
let options = ["Afghanistan", "Åland Islands", "Albania", "Algeria",
"American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua
and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria",
"Azerbaijan", "Bahamas", "Bahrain"];
options.forEach(option =>
optionList.add(new Option(option, option)));
}
//Get the person info
function newPerson() {
var person = {
name: document.getElementById("name").value,
age: Number(document.getElementById("age").value),
isMale: Boolean(document.getElementById("isMale").checked),
country: document.getElementById("country").value
};
//Check validation
if (!validateParameters(person)) {
return;
}
//fetch : get the web
fetch(`/api/newPerson`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(person),
})
.then(res => {
if (res.status == 201) {
alert(person.name + " added successfully");
window.location = "/personsData.html";
} else if (res.status == 400) {
alert("ERROR: Name already exist");
}
})
.catch(err => console.log(`ERROR : ${err}`));
}
/*
* Validation : person input
* Check if person name between 3-15
* Check if person age betwen 0-120
*/
function validateParameters(person) {
if (person.name.length < 3 || person.name.length > 15) {
alert("The name : " + person.name + " must contain more that 3
latters and below 15 ");
return false;
}
if (person.age < 0 || person.age > 120 || person.age == "") {
alert("The age " + person.age + " is wrong neew to be between 1-
120");
return false;
}
return true;
}
</script>
</head>
<body onload="loadData()">
<div class="center">
<label style="font-size:30px;">Name:</label>
<input style="font-size:20px;" type="text" id="name" placeholder="Your
name..." />
</div>
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Age:</label>
<input style="font-size:20px;" type="number" id="age" placeholder="Your
age..." />
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Is Male ? </label>
<input style="font-size:20px;" type="checkbox" id="isMale" />
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Country:</label>
<select style="font-size:20px;" id="country" placeholder="Your
country...">
</div>
<div class="center">
</select>
<br/>
<br/>
<input onclick="newPerson()" type="submit" value="ADD"></input>
</div>
</body>
</html>
个人数据.html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div {
height: 1500px;
width: 80%;
background-color: powderblue;
}
b.filds {
font-size: 30px;
color: rgb(99, 31, 189);
padding-right: 10px;
padding-left: 10px;
}
body {
color: rebeccapurple;
}
h1 {
text-decoration: underline;
}
</style>
<script>
//Add all persons to personView string and print the data to html page
function formatPersons(personList) {
var personView = "";
for (person of personList) {
personView += `<b class="filds">| Name:</b>
<b class="filds">${person.name}</b>,</b>
<b class="filds">| Age: </b>
<b class="filds"><b class="filds">${person.age}</b>,</b>
<b class="filds">| is Male: </b>
<b class="filds"><b class="filds">${person.isMale}</b>,</b>
<b class="filds">| Country: </b>
<b class="filds"><b class="filds">${person.country}</b>.</b>
<br\>`;
}
document.getElementById("body").innerHTML = personView;
}
//Load data from persons JSON
function getAllPersons() {
fetch(`/api/persons`)
.then(res => res.json())
.then(body => formatPersons(body.persons))
.catch(err => console.log(`Error: ${err}`));
}
</script>
</style>
</head>
<body onload="getAllPersons()">
<h1>Persons data</h1>
<div>
<p id="body"></p>
</div>
</body>
</html>
解决方案
当您点击 express 服务器时,默认情况下它会搜索 index.html 的路径“/”。在您的情况下,您没有同时定义两者。您应该能够使用 localhost:port/form.html" 和 localhost:port/personsData.html 访问您的两个页面。
推荐阅读
- sql - 写入以输出所有更新的 ID
- swift - Swift 展开问题,视图控制器堆栈未更新
- python - 在 Tkinter 中上传文件后自动关闭窗口
- c# - 从字符串解析为浮点数时如何修复统一FormatException?
- android - 具有不等正方形的Android网格布局
- postgresql - postgres 在 index_only 扫描中表现不佳(1.000.000+ 循环)
- vb.net - 是否可以过滤输入到用 VB 制作的控制台应用程序中的数据类型?
- firebase - 一个文档中可以存在多少个字段?
- c++ - 仅在本地主机上工作的模拟 HTTP 身份验证
- android - Android Pie 9.0 方向问题