So, I've been trying to make my first node.js project with a Skillshare teacher, however, while he doesn't run into this error, I did. I've read the code over but there is very little that I can do when I am a beginner to node.js. Here is the code. I would appreciate it if you can help me debug what is going on. I thank you in advance.
var http = require('http');
var url = require('url');
var StringDecoder = require('string_decoder').StringDecoder;
var server = http.createServer(function(req, res) {
//parse the URL
var parsedURL = url.parse(req.url, true);
//get the path
var path = parsedURL.pathname;
var trimmedPath = path.replace(/^\/+|\/+$/g, '')
//queryString
var queryStringObject = parsedURL.query;
//get the HTTP method
var method = req.method.toLowerCase();
//get the headers as an object
var headers = req.headers;
//get the payload, if any
var decoder = new StringDecoder('utf-8');
var buffer = '';
req.on('data', function(data) {
buffer += decoder.write(data);
});
req.on('end', function() {
buffer += decoder.end();
//Choose the handler this request should go to
var chosenHandler = typeof(router[trimmedPath]) !=='underfined' ? router[trimmedPath] : handlers.notfound;
//Construct the data object to send the handler
var data = {
'trimmedPath' : trimmedPath,
'queryStringObject' : queryStringObject,
'method' : method,
'headers' : headers,
'payload' : buffer
};
//Route the request to the handler
chosenHandler(data, function(statusCode, payload) {
statusCode = typeof(statusCode) == 'number' ? statusCode: 200;
payload = typeof(payload) == 'object' ? payload : {};
var payloadString = JSON.stringify(payload);
res.writeHead(statusCode);
res.end(payloadString)
//Log the path
console.log('Returning this respond: ', statusCode, payloadString);
});
});
});
server.listen(3000, function() {
console.log("Listening on port 3000")
});
//define the handler
var handlers = {};
//sample handler
handlers.sample = function(data,callback) {
callback(406, {'name' : 'sample handler'})
};
//not found handler
handlers.notfound = function(data, callback) {
callback(404);
};
//define a request router
var router = {
'sample' : handlers.sample
};
var chosenHandler = router[trimmedPath] || handlers.notfound;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With