0

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. 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. But I don't know specifically how I would specify a function.

  • 3
    Does a file called users.json exist in the root of your project? Also, please add the exact error code and stacktrace you receive. – Joseph Mar 30 '21 at 23:35
  • /addUser has only logic to read from the `users.json` file, there is no logic built to write the new user to the file, let alone to create the file. – Dshiz Mar 30 '21 at 23:37
  • @Joseph a file called users.json exists and works for the user list and specific user part, and as for error code it doesn't give one. The HTML just doesn't show anything and the Nodejs console says "unspecified" – Squibbles Mar 31 '21 at 01:31
  • @Dshiz so how would one go about making such a function to write a new user? – Squibbles Mar 31 '21 at 01:32
  • @Squibbles is there a users.json file? If not, you might need to re-read the instructions. – Dshiz Mar 31 '21 at 01:38
  • @Dshiz there is a users.json file and it works for the other commands just not the add and delete functions – Squibbles Mar 31 '21 at 01:40
  • @Squibbles you are only reading from the file in the /addUsers function. You are never writing to the file. The same thing is true for the /deleteUsers function. In both cases, you have to write to the file. – Dshiz Mar 31 '21 at 01:42
  • I posted an answer to cover the saving of data for your add/delete APIs. It doesn't, however, tell us why your console.log(data) is returning unspecified. You'll probably want to add more console.logs for data immediately after reading it and immediately after using JSON.parse on it to see how its getting cleared out. – Joseph Mar 31 '21 at 01:55

1 Answers1

0

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.

  2. You're converting "data" from a string to an object using JSON.parse. So far, so good.

  3. You're setting the property "user4" on data, which should now be a list of users. 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. Also, potential problem - you're setting the same key on the data object every time this request is made. You will continually overwrite the "user4" property each time, which will act as an update instead of an add. There's no way to determine what this code should be without see what you're POSTing into this API.

  4. You're setting data["user4"] equal to user["user4"], or more specifically the value of the "user4" property of user. 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):

    data["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. Here's a great post on how to write a string to a file: 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. 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).

Joseph
  • 865
  • 5
  • 20