【问题标题】:Import module with folder and passing data to module in nodejs使用文件夹导入模块并将数据传递给nodejs中的模块
【发布时间】:2020-08-15 23:23:45
【问题描述】:

我找到了关于的教程 Designing a clean REST API with Node.js (Express + Mongo)

github中的项目。

但问题是我没有理解路由的概念。

误解的部分是如何将httpRequest 数据传递给contact-endpoint 模块中的handle 方法?
因为handle方法在这里
export default function makeContactsEndpointHandler({ contactList }) { return async function handle(httpRequest) {

这是项目的index

import handleContactsRequest from "./contacts";
import adaptRequest from "./helpers/adapt-request";

app.all("/contacts", contactsController);
app.get("/contacts/:id", contactsController);

function contactsController(req, res) {
   const httpRequest = adaptRequest(req);
   handleContactsRequest(httpRequest)
       .then(({ headers, statusCode, data }) =>
            res.set(headers).status(statusCode).send(data)
       )
       .catch((e) => res.status(500).end());
}

这是adaptRequest

export default function adaptRequest (req = {}) {
   return Object.freeze({
       path: req.path,
       method: req.method,
       pathParams: req.params,
       queryParams: req.query,
       body: req.body
  })
}

这是handleContactsRequest 模块:

import makeDb from "../db";
import makeContactList from "./contact-list";
import makeContactsEndpointHandler from "./contacts-endpoint";

const database = makeDb();
const contactList = makeContactList({ database });
const contactsEndpointHandler = makeContactsEndpointHandler({ contactList });

export default contactsEndpointHandler;

这是contact-endpoint 模块的一部分:

export default function makeContactsEndpointHandler({ contactList }) {
    return async function handle(httpRequest) {
         switch (httpRequest.method) {
              case "POST":
                  return postContact(httpRequest);
              case "GET":
                  return getContacts(httpRequest);
         default:
             return makeHttpError({
                   statusCode: 405,
                   errorMessage: `${httpRequest.method} method not allowed.`,
             });
        }
   }

【问题讨论】:

    标签: node.js express node-modules


    【解决方案1】:

    makeContactsEndpointHandler 是一个返回函数 (async handle(xxx)) 的函数。

    handleContactsRequest 中,我们导出调用结果:makeContactsEndpointHandler({ contactList })。因此,async handle(xxx) 本身就是函数。

    所以,在index 中,当我们使用常量httpRequest 作为参数调用handleContactsRequest 时,我们实际上是在调用handle(xxx) 函数。 (我写了xxx 作为参数名,以突出两个httpRequest 声明之间的区别。)

    【讨论】:

    • 已理解,但我忘记在index 中包含一些内容,导入包含索引文件的文件夹handleContactsRequest 如何加载模块并获取httpRequest 参数?
    • 我从 nodejs 的文件夹中读取加载模块,但是handleContactsRequest 如何将数据传递给makeContactsEndpointHandler
    • i console.log(httpRequest) in handleContactsRequest 但得到错误 undefined ...
    • ## 更新了第一个代码 sn-p 中的问题,添加了导入 ##
    猜你喜欢
    • 2023-03-28
    • 2019-04-10
    • 2018-05-22
    • 2015-07-07
    • 2019-11-24
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多