“ selectedHandler”不是函数,节点JS

时间:2018-11-19 17:12:34

标签: javascript node.js rest api

我是Node JS的新手,最近我制作了所有API,这些API完全可以按我的意愿工作。但是,现在我希望其中一些(例如handler.home)也返回静态html模板。但是,现在我得到了如下错误。...

Server.js

const config = require('../config');

//Dependencies
const http = require('http');
const https = require('https');
//file system support to read files
var fs = require('fs');
//path module to access directories
var path = require('path');
var url = require('url');

//importing the handlers
var handlers = require('./handlers');

//importing helpers
var helpers = require('./helpers');

var stringDecoder = require('string_decoder').StringDecoder;


//server object to handle all the tasks
let server = {}

//creating a server from the https module which defines what to do when the server is created
server.httpsServerOptions = {
    'key': fs.readFileSync(path.join(__dirname, '/../https/key-pem')),
    'cert': fs.readFileSync(path.join(__dirname, '/../https/cert.pem'))
};

//creating a server from the http module which defines what to do when the server is created
server.httpServer = http.createServer(function(req, res){
    server.unifiedServer(req, res);
});

server.httpsServer = https.createServer(server.httpsServerOptions, function(req, res){
    server.unifiedServer(req, res);
});

server.unifiedServer = function(req,res){
    //steps of parsing a user request

    //GET the method of request -> get/put/delete/post
    var method = req.method.toLowerCase();
    //PARSE THE URL / get the url
    var parsedUrl = url.parse(req.url, true);
    var path = parsedUrl.pathname;
    var queryObject = parsedUrl.query;
    var trimmedPath = path.replace(/^\/+|\/+$/g, '');

    //Read Headers
    var urlHeaders = req.headers;

    var decoder = new stringDecoder('utf-8');
    var bufferPayload = '';

    //event handler when some data is recieved in the payload / body
    req.on('data', (data) => {

        bufferPayload += decoder.write(data);
    });

    req.on('end', () => {
        bufferPayload += decoder.end();

        //ROUTE TO A SPECIFIC HANDLER BASED ON ROUTING OBJECT, ROUTE TO NOTFOUND IF NOT FOUND
        var selectedHandler = typeof(server.router[trimmedPath]) !== 'undefined' ? handlers[trimmedPath] : handlers.notFound;
        //once the handler is specified, we need to send some data to it as expected by the handler
        var data  = {
            'headers': urlHeaders,
            'method': method,
            'pathname': trimmedPath,
            'payload': helpers.convertJSONstr2JSON(bufferPayload),
            'queryString': queryObject
        }
        //send the data and look for callback
        selectedHandler(data, (statusCode, payload, contentType) => {
            console.log("entered")
            //send a default status code of 200 if no status code is defined
            statusCode = typeof(statusCode) == 'number' ? statusCode : 200;
            //set contentType to json if no contentType is provided for rendering
            contentType = typeof(contentType) == 'string' ? contentType : 'json';
            if(contentType == 'json'){
                res.setHeader('Content-Type', 'application/json');
                payload = typeof(payload) == 'object' ? JSON.stringify(payload) : JSON.stringify({});
            }
            if (contentType == 'html'){
                res.setHeader('Content-Type', 'text/html');
                payload = typeof(payload) == 'string' ? payload : '';
            }
            res.writeHead(statusCode);

            //SEND THE RESPOSE FROM THE SERVER
            res.end(payload);

            //LOG IF YOU NEED TO THE CONSOLE
            if(statusCode == 200){
                //display in green
                console.log('\x1b[32m%s\x1b[0m',"response on ", method +" " +trimmedPath, " ->", statusCode);       
            }
            else {
                //for any non 200 status, display in red
                console.log('\x1b[31m%s\x1b[0m',"response on ", method +" " +trimmedPath, " ->", statusCode);
            }
        });
    });
};

server.router = {
    '' : handlers.home,
    'account/create': handlers.accountCreate,
    'account/edit': handlers.accountEdit,
    'account/deleted': handlers.accountDeleted,
    'session/create' : handlers.sessionCreate,
    'session/deleted' : handlers.sessionDeleted,
    'checks/create' : handlers.checksCreate,
    'checks/all': handlers.checkList,
    'checks/edit': handlers.checksEdit,
    'ping': handlers.ping,
    'api/users': handlers.users,
    'api/tokens': handlers.tokens,
    'api/checks': handlers.checks
};

//intitialise the server file
server.init = ()=>{

    server.httpServer.listen(config.httpPort, function(){
        console.log('\x1b[36m%s\x1b[0m',"the server is listening on port "+config.httpPort + " ["+config.envName+"] ");
    });

    server.httpsServer.listen(config.httpsPort, function(){
        console.log('\x1b[35m%s\x1b[0m',"the server is listening on port "+config.httpsPort + " ["+config.envName+"] ");
    });
};

module.exports = server;

handlers.js

/*
*This file stores all the handlers
*
*/


//dependencies
let dataLib = require('./data');
let helpers = require('./helpers');
let config = require('../config');

//main code
let handlers = {};

/*
*   HTML API HANDLERS BELOW
*
*/

handlers.home = function(data, callback){
    console.log("found index ->", data);
    callback(200, 'undefined', 'html');
};
module.exports = handlers;

我收到的错误是 enter image description here

现在,我要的是能够在contentType为html的情况下进行响应,而它现在无法正常工作。如果我不提供contentType并设置api的行为以返回json,则一切正常。有什么想法吗?

0 个答案:

没有答案
相关问题