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

时间:2018-10-31 09:40:36

标签: 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")});

form.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>

1 个答案:

答案 0 :(得分:0)

当您点击快递服务器时,默认情况下,它将在index.html中搜索路径“ /”。就您而言,您同时没有定义。您应该可以使用localhost:port / form.html“和localhost:port / personsData.html来访问两个页面。