Nodejs HTTP服务器中的自定义模块要如何获取PATH或者返回信息?

Nodejs HTTP服务器中的自定义模块要如何获取PATH或者返回信息?

//index.js var http = require(“http”); var api = require(“api”); //这是我自定义的模块

http.createServer(function(request, response) { api.api(url.parse(request.url).pathname); //可以这样把pathname给api函数,但是如果不给它pathname,api函数要如何获取pathname api.api(); //简而言之就是如何实现这个模块让它可以这样直接输出pathname??? response.writeHead(200, {“Content-Type”: “text/plain”}); response.write(“Hello World”); response.end(); }).listen(8888);

//api.js function api(pathname) { console.log(pathname); } exports.api = api;


4 回复

Nodejs HTTP服务器中的自定义模块要如何获取PATH或者返回信息?

问题描述

在Node.js的HTTP服务器中,我们希望自定义模块能够获取到请求的路径(pathname),而不仅仅是在创建服务器时传递该参数。如果自定义模块需要直接获取pathname,应该如何实现呢?

示例代码

首先,我们来看一下 index.js 文件:

// index.js
const http = require("http");
const url = require("url");
const api = require("./api");

http.createServer((request, response) => {
    const pathname = url.parse(request.url).pathname;
    api(pathname); // 传递 pathname 给 api 函数

    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8888);

接下来是 api.js 文件:

// api.js
function api(pathname) {
    console.log(pathname); // 输出路径名
}

module.exports = {
    api: (req, res) => {
        const pathname = url.parse(req.url).pathname;
        api(pathname); // 在内部处理请求和响应对象,并获取 pathname
    }
};

解释

  1. index.js

    • 创建HTTP服务器,并监听端口8888。
    • 使用 url.parse(request.url).pathname 获取请求的路径名,并将其传递给 api 函数。
  2. api.js

    • api 函数重新导出为一个接收 reqres 参数的函数。
    • 在这个函数内部,解析请求的URL并提取 pathname,然后调用原来的 api 函数并将 pathname 作为参数传递。

通过这种方式,api 模块可以直接处理请求和响应对象,并从中提取所需的信息,而无需每次调用时都显式地传递这些参数。这样可以提高代码的可维护性和复用性。


把req对象在实例化api类时丢进去

按照 express 等基于中间件的框架的思维,把和请求有关的变量和函数挂在 req 上,和响应有关的挂在 res 上,然后把这两个对象传到 api 模块里。

为了在自定义模块中获取HTTP请求的路径(即request.url中的pathname),你可以将请求对象传递给该模块,并从请求对象中提取url。以下是具体的实现步骤和示例代码:

示例代码

index.js

const http = require('http');
const url = require('url'); // 引入url模块
const api = require('./api');

http.createServer((request, response) => {
    const pathname = url.parse(request.url).pathname;
    
    // 将请求对象传递给api模块
    api.api(request, response);

    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}).listen(8888);

api.js

const url = require('url'); // 引入url模块

function api(request, response) {
    const pathname = url.parse(request.url).pathname;
    console.log(pathname);
}

module.exports.api = api;

解释

  1. 引入url模块:在api.js中引入url模块,以便解析URL。
  2. 修改api函数签名:让api函数接收requestresponse作为参数。
  3. 提取路径名:在api.js中使用url.parse(request.url).pathname来获取请求的路径名。
  4. 调用api函数:在index.js中,将requestresponse对象传递给api函数。

通过这种方式,api.js模块可以直接访问到HTTP请求的路径信息,而无需将其硬编码或在index.js中传递路径信息。

回到顶部