简体   繁体   中英

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

I've created MERN web apps where I had a client folder and a server folder, and the entire package was deployed on Heroku. I'm beginning my first React Native project now (using expo) and I read that I should be able to use the same stack, but I'm having a really hard time finding information about how to connect to a server and database when it's not packaged up in the same project.

In previous projects I connected to the database using a connection.js file:

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;

and a server.js file:

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}`);
  });
});

This was all placed in a server folder along with models, schemas, etc. at the root of the project. Now that I'm trying to figure out how to connect separate front and back ends for this native app, I'm lost as to how to get them connected. Any help would be appreciated!

This may help https://www.apollographql.com/docs/react/integrations/react-native/ and try using

 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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