node.js - NextJS/Vercel/MongoDB FetchError:对 http://localhost:3000/api/gear 的请求失败,原因:连接 ECONNREFUSED 127.0.0.1:3000
问题描述
我使用 NextJS 对 MongoDB 进行 API 调用。当我转到 API链接时,我看到返回的 MongoDB 查询。但是,当我尝试将该数据提取到网页时,我收到 500 内部服务器错误。函数日志显示以下错误:
2020-05-27T17:17:02.129Z 5a0c88b0-da63-4225-acf1-ea1d589ff438 ERROR FetchError: request to http://localhost:3000/api/gear failed, reason: connect ECONNREFUSED 127.0.0.1:3000
at ClientRequest.<anonymous> (/var/task/node_modules/next/dist/compiled/node-fetch/index.js:1:147710)
at ClientRequest.emit (events.js:310:20)
at Socket.socketErrorListener (_http_client.js:426:9)
at Socket.emit (events.js:310:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
message: 'request to http://localhost:3000/api/gear failed, reason: connect ECONNREFUSED 127.0.0.1:3000',
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED'
}
所有代码在运行 npm run dev 时都可以在本地运行,只是在托管到 Vercel 时无法运行。我只是不太明白为什么当我导航到 API 页面时它会返回 MongoDB 数据,但是当我尝试从另一个页面调用该 API 时却无法连接。
作为参考,我使用这个链接来构建我的数据库调用。
下面是失败页面的 getInitialProps 以及数据库中间件。
齿轮.jsx
import React, { Fragment } from "react"
import fetch from 'isomorphic-unfetch'
//Returned HTML here based on query. Left this part out to keep the issue simple.
export async function getServerSideProps() {
const res = await fetch('http://localhost:3000/api/gear')
const json = await res.json()
return { props: { gearArray: json } }
}
export default Gear;
api/gear.js
import nextConnect from 'next-connect';
import middleware from '../../middleware/database';
const handler = nextConnect();
handler.use(middleware);
handler.get(async (req, res) => {
let gear = await req.db.collection('gear').find({}).sort({gear: 1}).toArray();
res.json(gear);
});
export default handler;
数据库.js
import { MongoClient } from 'mongodb';
import nextConnect from 'next-connect';
const client = new MongoClient(process.env.MONGOURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
async function database(req, res, next) {
if (!client.isConnected()) await client.connect();
req.dbClient = client;
req.db = client.db('BassTabs');
return next();
}
const middleware = nextConnect();
middleware.use(database);
export default middleware;
解决方案
在 Vercel 上托管应用程序时,您需要将获取 URL 更改为https://my-bassist-chris.mybassistchris.now.sh/api/gear
,因为这是数据的来源。
在本地运行应用程序时,您使用localhost
.
推荐阅读
- python - 有没有办法在程序开始时显示 PyQt5 QMessageBox 而无需与之交互?
- terraform - Terraform 模块抛出“错误:属性块不足”
- google-sheets - 在多个电子表格之间共享和同步列数据
- c# - 命令行调用后从脚本中捕获错误
- java - 开放式 MPI 中是否可以使用运行时结构?
- google-app-maker - 关于 Google 应用制作工具中的自动完成的问题
- ios - 如何在第二个屏幕上更新存储在 Core Data 中的值并在第一个屏幕上显示更新的值?
- function - 在lua中拆分算术运算字符串
- javascript - Javascript使用纯javascript在悬停时显示图像替代
- google-sheets - 将列表重复 N 次 Google 表格