【问题标题】:How to call NextJs api that fetch data from MongoDB?如何调用从 MongoDB 获取数据的 NextJs api?
【发布时间】:2022-07-15 18:34:58
【问题描述】:

我创建了一个从 MongoDb 获取数据的 products api。

import dbConnect from "../../../lib/mongodb";
import Products from "../../../models/Products";

export default async function handler(req, res) {
  const { method } = req;
  dbConnect();
  if (method === "GET") {
    try {
      const products = await Products.find();
      res.status(200).json(products);
    } catch (err) {
      res.status(500).json(err);
    }
  }

  if (method === "POST") {
    try {
      const product = await Products.create(req.body);
      res.status(201).json(product);
    } catch (err) {
      res.status(500).json(err);
    }
  }
}

我已成功连接到数据库并在 localhost 中获取数据。但是当我在 vercel 上部署它时,出现 500 内部错误。我在 react-admin dataProvider.js 中使用这个 api 就像那样

import { fetchUtils } from "react-admin";

import { stringify } from "query-string";
const httpClient = fetchUtils.fetchJson;

const dataProvider = {
  getList: (resource, params) => {
    const { page, perPage } = params.pagination;
    const query = {
      range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
    };
    const url = `/api/${resource}?${stringify(
      query
    )}`;  //here the API that I call

    return httpClient(url).then(({ headers, json }) => ({
      data: json.map((resource) => ({ ...resource, id: resource._id })),
      total: parseInt(headers.get("content-range").split("/").pop(), 10),
    }));
  },
};

export default dataProvider;

这里是开发者工具中network的截图

在本地 生产中

我想分享我的域链接 https://electronic-products47.vercel.app/

【问题讨论】:

  • 您能告诉我们您在 Vercel 日志中遇到的服务器错误吗?

标签: reactjs mongodb next.js react-admin


【解决方案1】:

我认为,在 Monge DB 网络访问中,您需要将 0.0.0.0/0 IP 添加到“白名单”中,以便您的 Vercel 服务器不会被 Mongo DB 数据库阻止。

enter image description here

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 2021-04-22
    • 2020-10-08
    • 2022-07-31
    • 2022-12-11
    • 2018-03-11
    • 2019-09-29
    • 2021-10-08
    相关资源
    最近更新 更多