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.