J'ai commencé à étudier node.js. Je vous pose des questions tout en étudiant. Lorsque j'exécute mon code (serveur) et que je me connecte à localhost, cela ne fonctionne pas correctement.
Voici mon code :
index.js
var server = require('./server');
var router = require('./router');
var requestHandlers = require('./requestHandlers');
var handle = {};
handle['/'] = requestHandlers.view;
handle['/view'] = requestHandlers.view;
handle['/create'] = requestHandlers.create;
server.start(router.route, requestHandlers.handle);
server.js
var http = require('http');
var url = require('url');
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log('\nrequest for ' + pathname + ' received.');
response.writeHead(200, {'Content-Type' : 'text/plain'});
// route(handle, pathname); // injected function call
var content = route(handle, pathname);
response.write(content);
response.end();
}
http.createServer(onRequest).listen(8000);
console.log('server has started.');
}
exports.start = start;
router.js
function route(handle, pathname) {
console.log('about to route a request for ' + pathname);
if (typeof handle[pathname] === 'function') {
return handle[pathname]();
} else {
console.log('no request handler found for ' + pathname);
return "404 Not found";
}
}
exports.route = route;
requestHandlers.js
function view(response) {
console.log('request handler called --> view');
return "Hello View";
}
function create(response) {
console.log('request handler called --> create');
return "Hello Create";
}
exports.view = view;
exports.create = create;