简体   繁体   中英

How to check if a request is for javascript (or other types) when using Node.js without using any middleware?

I am thinking one way to check it is to parse the last three characters of the url to see if it matches .js but then if the url contains parameters, it wouldn't work. I can also check if the request header has Accept but not all request has this header.

The only incoming information with the request is the URL and the HTTP headers. So, you have to base your decision about whether this is a script request or not on what you see in those.

If you just want to look at the filename in the URL, you can parse off the query string pretty easily and then examine just the filename. While there are lots of pre-tested, already written libraries that will parse a URL into all its components for you, if you really can't use any already written code (which seems almost like a crime to me since that's half the point of an open source world), then you can just write a simplified parser that just does what you need.

Here's a fairly simple one:

function getExtensionFromUrl(url) {
    // remove query string (if present)
    let qIndex = url.indexOf("?");
    if (qIndex !== -1) {
        url = url.slice(0, qIndex);
    }
    // remove protocol
    let dIndex = url.indexOf("://");
    if (dIndex !== -1) {
        url = url.slice(dIndex + 3);
    }
    // remove domain
    dIndex = url.indexOf("/");
    if (dIndex !== -1) {
        url = url.slice(dIndex + 1);
    } else {
        // apparently no path
        url = "";
    }
    // remove trailing slash (if present)
    if (url.charAt(url.length - 1) === '/') {
        url = url.slice(0, -1);
    }
    // now get file extension
    let match = url.match(/\.[^.\/]+$/);
    if (match) {
        return match[0];
    } else {
        return "";
    }
}

Some test cases here: https://jsfiddle.net/jfriend00/1yekL5by/


Or, since the url package is built-into node.js, you could presumably use that:

const urlLib = require('url');

function getExtensionFromUrl(url) {
    let path = urlLib.parse(url).pathname;

    // remove trailing slash (if present)
    if (path.charAt(path.length - 1) === '/') {
        path = path.slice(0, -1);
    }
    // now get file extension
    let match = url.match(/\.[^.\/]+$/);
    if (match) {
        return match[0];
    } else {
        return "";
    }
}

Node.js has a module to work with URLs. Try this...

 const url = require('url'); const urlStr = 'http://www.example.com/scripts/test.js?x=y'; const parsedURL = url.parse(urlStr); const path = parsedURL.pathname; if (path.lastIndexOf('.js') === path.length - 3) { // extension is a JS file } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM