首页 > 解决方案 > 路由不能正常工作

问题描述

在下面的代码中,当我尝试使用 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");
});

我已根据从请求中收到的方法拆分消息。

标签: javascriptnode.js

解决方案


看起来您正在比较 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 中的响应。

在此处输入图像描述


推荐阅读