node.js - 如何在 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" 但它不起作用,如何解决这个问题
解决方案
推荐阅读
- python - 如何在熊猫中读取和规范化以下json?
- django - 在配置 django 静态和媒体文件时获取 BlobNotFound
- excel - 在 Excel VBA 中取消选择图表
- javascript - 睡着时移动设备上的 window.speechSynthesis
- javascript - 未捕获的 TypeError:无法在 Chrome 中的 Javascript 中设置属性“innerHTML”为 null
- kubernetes - kunernetes Service 和 Ingress 的区别
- javascript - react-select 2 设置值/标签
- ios - 从使用 MessageKit 创建的 ChatViewController 推送其他 ViewController
- python - Keras Tuner 抛出 InvalidArgumentError
- python - Python Setuptools:添加没有“main”功能的脚本作为“console_scripts”入口点的快速方法