首页 > 解决方案 > 如何在 express api 中导入模块

问题描述

我想通过编写一个小连接模块将 Elasticsearch 连接到我的 express rest API:

db.connection.js

import { Client } from 'elasticsearch'
const client = new Client({
    hosts: ['http://localhost:9200']
});
client.ping({
    requestTimeout: 30000,
}, function (error) {
    if (error) {
        console.error('Elasticsearch cluster is down!');
    } else {
        console.log('Everything is ok');
    }
});

module.exports = Client;
 

当尝试在我的 app.js 中导入模块时,服务器返回错误 [ERR_MODULE_NOT_FOUND]:找不到模块

应用程序.js

import http from 'http'
import express from 'express'
import morgan from 'morgan'
import bodyParser from 'body-parser'
import json from 'express'
import helmet from 'helmet'
import cors from 'cors'
import cookieParser from 'cookie-parser'
import dotenv from 'dotenv'
import connection from './config/db.connection'
const app = express();


// allow cors requests from any origin and with credentials
app.use(cors({ origin: (origin, callback) => callback(null, true), credentials: true }));
// set security HTTP headers
app.use(helmet())
// parse json request body
app.use(json())
// logger
app.use(morgan('dev'))
// parses cookies attached to the client request object
app.use(cookieParser());

app.use(express.json());

app.use(express.urlencoded({
    extended: true
}));

app.use(dotenv.config)

// start server
const port = process.env.NODE_ENV === 'production' ? (process.env.PORT || 80) : 4000;
app.listen(port, () => {
    console.log('Server listening on port ' + port);
});

connection.cluster.health({}, function (err, resp, status) {
    console.log("-- Client Health --", resp);
});

app.get('/', (req, res) => {
    return res.send({ project: 'fwinr' })
});

我在 package.js 中添加了 ' "type": "module" 但它不起作用,如何解决这个问题

标签: node.jsapiexpressecmascript-6module

解决方案


推荐阅读