簡體   English   中英

如何將 React Native 應用程序連接到遠程 MongoDB 數據庫?

[英]How do I connect a React Native app to a remote MongoDB Database?

我創建了 MERN web 應用程序,其中我有一個客戶端文件夾和一個服務器文件夾,並且整個 package 部署在 Heroku 上。 我現在開始我的第一個 React Native 項目(使用 expo),我讀到我應該能夠使用相同的堆棧,但是我很難找到有關如何連接到服務器和數據庫的信息。沒有打包在同一個項目中。

在以前的項目中,我使用 connection.js 文件連接到數據庫:

const mongoose = require('mongoose');

mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/database-name', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
  useFindAndModify: false
});

module.exports = mongoose.connection;

和一個 server.js 文件:

const express = require('express');
const path = require('path');
// import ApolloServer
const { ApolloServer } = require('apollo-server-express');
const { typeDefs, resolvers } = require('./schemas');

const { authMiddleware } = require('./utils/auth');
const db = require('./config/connection');

const PORT = process.env.PORT || 3001;
const app = express();
// create a new Apollo server and pass in our schema data
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: authMiddleware
});

// integrate our Apollo server with the Express application as middleware
server.applyMiddleware({ app });

app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// Serve up static assets
if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, '../client/build')));
}

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../client/build/index.html'));
});

db.once('open', () => {
  app.listen(PORT, () => {
    console.log(`API server running on port ${PORT}!`);
    // url to test GQL API
    console.log(`Use GraphQL at http://localhost:${PORT}${server.graphqlPath}`);
  });
});

這一切都與項目根目錄下的模型、模式等一起放置在服務器文件夾中。 現在我正試圖弄清楚如何為這個本機應用程序連接單獨的前端和后端,我不知道如何連接它們。 任何幫助,將不勝感激!

這可能會幫助https://www.apollographql.com/docs/react/integrations/react-native/並嘗試使用

 import { ApolloClient, InMemoryCache, ApolloProvider, } from "@apollo/client"; const client = new ApolloClient({ uri: "/graphql", cache: new InMemoryCache() }) const App = () => { return ( <NavigationContainer> <ApolloProvider client={client}> {/*other components*/} </ApolloProvider> </NavigationContainer> ); }; export default App;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM