简体   繁体   English

Node.js - 如何在 HTML 中使用复杂的 function,例如“addUser”

[英]Node.js - How do I use a complex function in HTML like “addUser”

I was given an assignment in class for making a basic ReSTFul Web Application, and received a sample to create mine off of, but only 2 of the 4 routes worked and I'm very new so I can't figure out why the other functions aren't working.我在 class 中获得了一项任务,用于制作基本的 ReSTFul Web 应用程序,并收到了一个样本来创建我的,但 4 条路线中只有 2 条有效,而且我很新,所以我不知道为什么其他功能不工作。 The code looks like:代码如下所示:

//setup
var express = require('express');
var app = express();
var fs = require("fs");

//run the server
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
   console.log("Example app listening at http://%s:%s", host, port)
})

//http://localhost:8081
//general route

//data for existing users located in "users.json"
//here is the refer

app.get("/", function(req,res){

  var msg=""

  msg += "<center><h1> This is the default page </h1></center>"

  msg += " use the following <br />"

  msg += " http://localhost:8081/listUsers <br />"

  msg += " http://localhost:8081/addUser <br />"

  msg += " http://localhost:8081/deleteUser <br />"

  msg += " http://localhost:8081/(Put id# here) <br />"

 

  res.send(msg);

});

//To find a list of users
app.get('/listUsers', function (req, res) {
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
      console.log( data );
      res.end( data );
   });
})

//To add a user to the list

var user = {
   "user4" : {
      "name" : "mohit",
      "password" : "password4",
      "profession" : "teacher",
      "id": 4
   }
}

app.post('/addUser', function (req, res) {
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
     //First read existing users.
      data = JSON.parse( data );
      data["user4"] = user["user4"];
      console.log( data );
      res.end( JSON.stringify(data));
   });
})

//to show details of user by id#
app.get('/:id', function (req, res) {
   // First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
      var users = JSON.parse( data );
      var user = users["user" + req.params.id] 
      console.log( user );
      res.end( JSON.stringify(user));
   });
})

var id = 2;

//to delete a user

app.delete('/deleteUser', function (req, res) {
   // First read existing users.
   fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
      data = JSON.parse( data );
      delete data["user" + 2];
       
      console.log( data );
      res.end( JSON.stringify(data));
   });
})

The functions for listing users and specifying users work, but the addUser and deleteUser say "unspecified," leading me to believe that the ( data ) part may not be properly specified.列出用户和指定用户的功能有效,但是 addUser 和 deleteUser 说“未指定”,这让我相信 (data) 部分可能没有正确指定。 But I don't know specifically how I would specify a function.但我不知道具体如何指定 function。

Okay, there are a few issues going on here.好的,这里有一些问题。 First of all, it helps to walk through your code line by line to see what its doing, so you can try to figure out what you're missing:首先,它有助于逐行浏览您的代码以查看它在做什么,因此您可以尝试找出您缺少什么:

  1. You're reading the contents of users.json as a string using fs.readFile, which gets put in the variable "data" in your callback function.您正在使用 fs.readFile 将 users.json 的内容作为字符串读取,该字符串被放入回调 function 中的变量“data”中。

  2. You're converting "data" from a string to an object using JSON.parse.您正在使用 JSON.parse 将“数据”从字符串转换为 object。 So far, so good.到目前为止,一切都很好。

  3. You're setting the property "user4" on data, which should now be a list of users.您正在为数据设置属性“user4”,现在应该是用户列表。 This may or may not be correct depending on what the structure is for your users - if its an array, this code won't work.这可能正确也可能不正确,具体取决于您的用户的结构 - 如果它是一个数组,则此代码将不起作用。 If its an object where each key is the username, you'll be fine here.如果它是一个 object ,其中每个键都是用户名,那么这里就可以了。 Also, potential problem - you're setting the same key on the data object every time this request is made.此外,潜在的问题- 每次发出此请求时,您都在数据 object 上设置相同的键。 You will continually overwrite the "user4" property each time, which will act as an update instead of an add.您每次都会不断地覆盖“user4”属性,这将充当更新而不是添加。 There's no way to determine what this code should be without see what you're POSTing into this API.如果不查看您在此 API 中发布的内容,则无法确定此代码应该是什么。

  4. You're setting data["user4"] equal to user["user4"], or more specifically the value of the "user4" property of user.您将 data["user4"] 设置为等于 user["user4"],或者更具体地说,设置为 user.user 的 "user4" 属性的值。 First issue - user is not defined anywhere.第一个问题 - 用户未在任何地方定义。 If this was data that was sent in the body of the POST, you'll want to read it from the body - probably something like (again, dependent on the format of data you're sending during your POST):如果这是在 POST 正文中发送的数据,您需要从正文中读取它 - 可能类似于(同样,取决于您在 POST 期间发送的数据格式):

    data["user4"] = req.body.user;数据["user4"] = req.body.user;

  5. You're logging the full list of users.您正在记录完整的用户列表。 No problem here, good for visibility while debugging.这里没问题,有利于调试时的可见性。

  6. You're sending back the list of users you read from the file, plus the single user you just added.您正在发回您从文件中读取的用户列表,以及您刚刚添加的单个用户。

There's a step missing here - you never saved the updated list of users in any way.这里缺少一个步骤 - 您从未以任何方式保存更新的用户列表。 Some type of data should be returned to the user, but the next time you call add or get (or any other method), the user you just defined won't be present, since it was never added to users.json.某些类型的数据应该返回给用户,但是下次调用 add 或 get(或任何其他方法)时,您刚刚定义的用户将不存在,因为它从未添加到 users.json。 Here's a great post on how to write a string to a file: Writing files in Node.js这是一篇关于如何将字符串写入文件的精彩文章: Writing files in Node.js

It will probably end up looking like this:它可能最终看起来像这样:

fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
 //First read existing users.
  data = JSON.parse( data );
  data["user4"] = user["user4"];
  console.log( data );
  
  // Convert your updated user object into a JSON string
  var strData = JSON.stringify(data);
  
  // Write the updated JSON string out to the file
  fs.writeFile(__dirname + "/" + "users.json", strData, function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved!");
  }); 
  
  res.end( JSON.stringify(data));
});

This covers the addUser endpoint, but you'll need to introduce similar changes for your deleteUser endpoint.这涵盖了 addUser 端点,但您需要为您的 deleteUser 端点引入类似的更改。 If you're having trouble past this point, I'd recommend adding the contents of users.json to your question, as well as adding more detail on what you get back when you make the call into addUser and deleteUser (you can view the response body in Chrome dev tools -> Network tab).如果您在这一点上遇到问题,我建议您将 users.json 的内容添加到您的问题中,并添加有关在调用 addUser 和 deleteUser 时返回的内容的更多详细信息(您可以查看Chrome 开发工具中的响应正文 -> 网络选项卡)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM