【问题标题】:Not able to export function in nodejs无法在nodejs中导出功能
【发布时间】:2021-12-15 01:23:37
【问题描述】:

我在其中一个文件中定义了一个函数服务

import Category from '../models/Category.js';

export const AllCategories = () => {
        console.log('hit');
        const cursor =  Category.find({});
        console.log(cursor);
        return cursor
}


export default {AllCategories}

我在控制器文件中导入这个

import express from 'express';
import categoryService from '../services/categories.js'
const router = express.Router();

export const getCategories = async(req,res) => {
    try {
        const categoriesInfo = categoryService.AllCategories
        res.status(200).json(categoriesInfo)
    } catch (error) {
        res.status(404).json({ message: error.message });
    }
}

export default router;

但问题是 AllCategories 没有运行,这里出了什么问题

我也尝试添加 async/await

import Category from '../models/Category.js';

export const AllCategories = async () => {
    try {
        console.log("hit");
        const cursor =  await Category.find({});
        console.log(cursor);
        return cursor
    } catch (error) {
       return error 
    }
}


export default {AllCategories}

但还是没有运气

【问题讨论】:

    标签: javascript node.js ecmascript-6


    【解决方案1】:

    你不能在 node.js 中默认使用 ES module or ESM 语法。您要么必须使用CommonJS 语法,要么必须执行以下操作之一。

    1. 将文件扩展名从.js更改为.mjs
    2. 在最近的package.json 文件中添加一个名为type 的字段,其值为module

    【讨论】:

      【解决方案2】:

      您没有调用该函数,这会将其保存在变量categoriesInfo中:

      const categoriesInfo = categoryService.AllCategories
      

      获取它的返回值:

      const categoriesInfo = await categoryService.AllCategories();
      

      注意:如果您正在执行数据库事务,我认为您需要将其设为 async,因此请保留第二个版本并对其进行测试。

      【讨论】:

        猜你喜欢
        • 2017-03-19
        • 2019-10-27
        • 1970-01-01
        • 2018-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-06
        • 1970-01-01
        相关资源
        最近更新 更多