我想在 next.js 中使用弹性搜索进行日志收集,但出现此错误:
⨯ node:console
Module build failed: UnhandledSchemeError: Reading from "node:console" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.
Import trace for requested module:
node:console
./node_modules/undici/lib/mock/pending-interceptors-formatter.js
./node_modules/undici/lib/mock/mock-agent.js
./node_modules/undici/index.js
./node_modules/@elastic/transport/lib/connection/UndiciConnection.js
./node_modules/@elastic/transport/lib/connection/index.js
./node_modules/@elastic/transport/index.js
./node_modules/@elastic/elasticsearch/index.js
./src/lib/logger.ts
这是我的代码
// src/lib/logger.ts
import { Client } from "@elastic/elasticsearch";
const client = new Client({
node: "http://localhost:9200/",
});
export default class Logger {
static async log(index: string, body: object) {
await client.index({ index, body });
}
}
// src/middleware.ts
import { NextRequest } from "next/server";
import Logger from "@/lib/logger";
export async function middleware(request: NextRequest) {
// ...
Logger.log("cb-request-logs", {
user: session.user._id,
url: request.url,
userAgent: request.headers.get("User-Agent"),
});
// ...
}
我的环境:
节点 v20
nextjs v14.2.7
@elastic/elasticsearch ^8.15.0
我注意到您使用的节点地址是
http
而不是 https
。 这是故意的吗? (如果没有,请尝试使用node: "https://localhost:9200"
。
注意:我删除了结尾的“/”,所以
node: "https://localhost:9200"
而不是node: "https://localhost:9200/"
)
Elasticsearch 默认需要 https
快速检查:您可以通过运行这些命令来测试端点来检查您的 Elasticsearch 是否正常运行(另外,您使用的是 Mac 还是 Docker?根据系统的不同,命令略有不同):
麦克:
curl --cacert $ES_HOME/config/certs/http_ca.crt -u elastic:$ELASTIC_PASSWORD https://localhost:9200
码头工人:
curl --cacert http_ca.crt -u elastic:$ELASTIC_PASSWORD https://localhost:9200
如果出现错误,您可以尝试分别在 Mac 和 Docker 上进行安装。
elasticsearch.yml
) 并将以下设置从 true 更改为 false:xpack.security.transport.ssl.enabled: true
xpack.security.http.ssl.enabled: true
再次强调,第 3 点不是推荐的方法,但适合学习/实验。