在下面的代码中,当我尝试使用get方法打“ / hello”路由时,得到以下响应。除其他使用get方法的“ / hello”路由外,其他所有路由都工作正常。为什么会这样?
var http = require('http');
var url = require('url');
var stringDecoder = require('string_decoder').StringDecoder;
var server = http.createServer(function(req,res){
//parse the URL and get the path if we pass true as paramater it will act as query string
var parsedURL = url.parse(req.url,true);
//Get the path alone
var path = parsedURL.pathname;
//Trimm the URL
var trimmedpath = path.replace(/^\/+|\/+$/g,'');
//Get the method
var method = req.method.toLowerCase();
//Get the headers
var headers = req.headers;
//get the querystring as an object
var queryStringObject = parsedURL.query;
//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();
//Generate the data
var data = {
'method' : method,
'headers' : headers,
'trimmedpath' : trimmedpath,
'queryStringObject' : queryStringObject
}
var Handler = routes[trimmedpath];
var chosenHandler = typeof(Handler) !== 'undefined' ? Handler : handlers.notfound;
chosenHandler(data,function(statuscode,payload){
statuscode = typeof(statuscode) == 'number' ? statuscode : 300;
payload = typeof(payload) == 'object' ? payload : {};
console.log(payload);
var payloadString = JSON.stringify(payload);
//set the content type to view as object
res.setHeader('Content-Type','application/json');
res.writeHead(statuscode);
res.end(payloadString);
});
//Sending the response
console.log(buffer);
console.log(Handler,chosenHandler);
res.end("hello world");
});
});
var handlers = {};
handlers.hello = function(data,callback){
if(data.method == 'post'){
callback(404,{'Message' : 'You have hitted the post route'});
}
if(data.method == 'get'){
callback(143,{'message': 'you have hitted the get route'});
}
}
handlers.ping = function(data,callback){
callback(999,{'message':'ping route'});
}
handlers.notfound = function(data,callback){
callback(600,{'Message' : 'Major issue'});
}
var routes = {
'ping' : handlers.ping,
'hello' : handlers.hello
}
server.listen(3000,function(){
console.log("server started listening in the port 3000");
});
我已根据从请求中收到的方法拆分了邮件。
答案 0 :(得分:1)
您似乎在比较小型的HTTP方法
handlers.hello = function(data,callback){
if(data.method === 'POST'){
callback(404,{'Message' : 'You have hitted the post route'});
}
if(data.method === 'GET'){
callback(143,{'message': 'you have hitted the get route'});
}
}
我建议您使用一些已经构建好的路由器来处理多种情况,而又不增加代码长度。
更新
考虑到您已经使用了小写的http方法,可以看到在不修改您的代码的情况下调用了hello;
{ message: 'you have hitted the get route' }
[Function] [Function]
{ Message: 'You have hitted the post route' }
[Function] [Function]
还有POSTMAN中的响应。