javascript - 无法获取/nodeJS 问题,为什么我会收到此消息?

标签 javascript node.js

请帮忙 - 我在 NodeJS 应用程序中收到 Cannot Get/ 。为什么我会收到此消息? 我知道它就在这里,抱歉,但我不明白为什么会收到这条消息。 我已经尽了一切努力,但还是没明白。

............ ...................... ...................... ...................... …………

enter image description here

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>

personsData.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 访问这两个页面。

关于javascript - 无法获取/nodeJS 问题,为什么我会收到此消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53080361/

相关文章:

javascript - 如何编写/更改查询字符串而不导致浏览器加载新页面

javascript - 创建一个类并调用它的属性 (javascript)

node.js - 如何使用 Electron 生成器将 v8 快照打包到 exe 中?

node.js - 从 nodeJS 读取 PDF 文档属性

javascript - Node.js promise 不强制函数的顺序执行

javascript - 在 ES6 中,第一次调用迭代器的 `next` 方法时参数会发生什么变化?

JavaScript 的固执

javascript - JS 用链接替换字符?

node.js - ExpressJS 动态生成页面 - 搜索引擎会根据查询参数创建列表吗?

node.js - 如何将 Node.js 应用程序正确连接到 Cassandra Node ?