繁体   English   中英

将Mongodb数据库连接公开到Next.js 6应用程序中的页面

[英]Expose mongodb database connection to pages in Next.js 6 app

我正在使用Next.js v6构建应用程序,我想用本地mongodb数据库的结果填充页面。

理想情况下,我想做一些与本教程中的示例一样简单的事情,但是除了使用api fetch之外,只需向本地主机上的mongodb发送查询即可。

Next.js教程中的示例

import Layout from '../components/MyLayout.js'
import Link from 'next/link'
import fetch from 'isomorphic-unfetch'

const Index = (props) => (
  <Layout>
    <h1>Batman TV Shows</h1>
    <ul>
      {props.shows.map(({show}) => (
        <li key={show.id}>
          <Link as={`/p/${show.id}`} href={`/post?id=${show.id}`}>
            <a>{show.name}</a>
          </Link>
        </li>
      ))}
    </ul>
  </Layout>
)

Index.getInitialProps = async function() {
  const res = await fetch('https://api.tvmaze.com/search/shows?q=batman')
  const data = await res.json()

  console.log(`Show data fetched. Count: ${data.length}`)

  return {
    shows: data
  }
}

export default Index

我的问题是尝试使数据库连接并公开到应用程序,以便我可以在名为resources.js的页面上执行类似的操作:

import Layout from '../components/Layout'
import Link from 'next/link'

const Resources = (props) => {
    <Layout>
        <h3>Resources</h3>
        <ul style={listStyle}>
            {props.resources.map(({resource}) => (
                <li key={resource._id}>
                    <Link href={resource.link}>
                        <a>{resource.title}</a>
                    </Link>
                </li>
            ))}
        </ul>
    </Layout>
};

Resources.getInitialProps = async function() {  

    // get query from mongo DB
    // req is 'undefined' -- I want to see the db here
    const list = await req.db.get('resources').find();
    return list;

}

export default Resources;

但是我不知道如何以可以从应用程序中任何位置的页面访问的功能公开数据库。 似乎旧的示例教程使用了诸如server.use((req, res, next) => { req.db = dbToExpose }); 在主要的index.js文件中,但这似乎不适用于Next.js v。6?

例如, 教程中的此示例存储库似乎不适用于最新版本的Next.js。 当您尝试从一个页面访问它时,暴露在数据库中的req.db槽显示为“未定义”。 但是也许我错过了其他一些问题。

这是我在基本服务器文件中尝试公开的数据库,以便可以从pages/文件访问它:

const express = require('express')
const next = require('next')
const monk = require('monk')('localhost/myDatabase')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare()
.then(() => {
  const server = express()

  // This is not working to expose the db!
  server.use((req, res, next) => {
    req.db = monk
    next()
  });

  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})
.catch((ex) => {
  console.error(ex.stack)
  process.exit(1)
})

您不应该在Nextjs页面中公开任何安全数据或进行数据库连接。 这篇文章展示了使用不带api的NextJs连接数据库的方法

您需要将您的Mongo数据库包装在一个API中,您可以将其与下一个服务器一起使用以避免CORS问题。 Next不会将Express请求公开给页面,因为这在客户端渲染中不可用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM