jeudi 12 juillet 2018

node.js allow only supported methods

the following is the start of an API I'm trying to write as part of my lessons,the course is strictly node.js without any frameworks.

My attempt is to reject request with 400 if the request method is not allowed. (if method in methoArr then allow else reject)

var http = require('http');
var fs = require('fs');
const url = require('url');
var os = require('os');
var helpers = require('./helperFunctions');
var cl = console.log.bind(console);

//init server and listen 
http.createServer(function(req, res) {
    //define req.url as array
    let qs = url.parse(req.url).pathname;
    //deal with favico request
    if (req.url === '/favicon.ico') {
        res.writeHead(200, {
            'Content-Type': 'image/x-icon'
        });
        res.end();
        return;
    }
    //return if method not allowed
    const methodArr = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'];
    var allowedMethod = true;
    cl(typeof req.method, typeof methodArr[0]);
    if (
        req.url != methodArr[0] &&
        req.url != methodArr[1] &&
        req.url != methodArr[2] &&
        req.url != methodArr[3] &&
        req.url != methodArr[4] &&
        req.url != methodArr[5]
    ) {
        allowedMethod = false;
    }
    if (allowedMethod) {
        // cl('req.url: ', qs, 'helpers: ', helpers, 'req method: ', req.method);
        res.writeHead(200);
        res.write('end url: ' + qs + ' method: ' + req.method);
    } else {
        res.writeHead(400);
        res.write(req.method + ' method not allowed\n' + 'methodArr#: ' + methodArr[0]);
    }
    res.end();
}).listen(3000, 'localhost');

the IF logic seems ok but obviously not...tried a switch but same issue. I would appreciate if you can explain the error in my logic.

Aucun commentaire:

Enregistrer un commentaire