将 React Native 连接到后端(使用 Express)

Hooking up React Native to back-end (with Express)

我用 React Native 做了一个 UI,还有一个 Cheerio.js scraper(用 Cron Job 每天激活一次)我会用来从网络上抓取某些数据,所以它可以在 UI 中呈现。但是,我不知道如何link他们两个。

我很确定我可以用 Express 做到这一点(我最喜欢后端),但是有人能确切地告诉我我需要做什么才能将我的前端连接到后端吗?结束?

以防万一,我是一名初级开发人员(前端比后端更好)所以请让您的回答简单明了。即使您的回答更具概念性,而不是基于代码,我也会非常感激。

假设您正在与使用 Express 构建的 API 通信,然后按照文档中的描述使用 fetchhttps://facebook.github.io/react-native/docs/network.html

API

我对 GraphQL 作为 REST 的替代品感到非常满意。但是,有很多方法可以通过 api 进行连接。您的客户端需要 link 到您的服务器 运行,并且您的服务器需要启用它。

教程

我认为我无法比本教程更好地解释它(在 Github 上有示例):https://medium.com/react-native-training/react-native-with-apollo-server-and-client-part-1-efb7d15d2361

https://medium.com/react-native-training/react-native-with-apollo-part-2-apollo-client-8b4ad4915cf5

并遵循 Stephen Grider 在 Udemy 上的教程,以更深入地了解 GraphQL。他在他的教程中使用的是 React 而不是 React Native,但语法仍然非常接近。 https://www.udemy.com/graphql-with-react-course/learn/v4/overview

重要通知 - 第一个教程使用“apollo-server”,而 udemy 的教程使用 graphql。 apollo-server 经常变化,graphql 可能更清晰。

例子

这是我在两者之间的桥梁的样子。最大的困难是处理应用程序前端版本 (Next.js) 的 Cors,并发现可以在 http://10.0.3.2:8080/graphql(可能会有所不同)而不是 localhost:8080 上访问服务器。

我的index.android.js(客户端):

import React from 'react'
import { AppRegistry } from 'react-native'
import App from './app'

import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { ApolloProvider } from 'react-apollo'

const Client = () => {
  const networkInterface = createNetworkInterface({
   uri: 'http://10.0.3.2:8080/graphql'
  })
  const client = new ApolloClient({
    networkInterface
  });
  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>)
}

AppRegistry.registerComponent('apolloclient', () => Client);

我的app.js服务器端

const express = require('express');
// const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const chalk = require('chalk');

// New imports
// NEVER FORGET to require the models,
// in which schemas are registered for a certain model
// forgetting it would throw "Schema hasn't been registered for model..."
const models = require('./models');
const expressGraphQL = require('express-graphql');
const schema = require('./schema/schema');

const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// My mongoLab URI
const MONGO_URI = 'mongodb://xxx:xxx@xxx.mlab.com:xxx/xxx';

// mongoose's built in promise library is deprecated, replace it with ES2015 Promise
mongoose.Promise = global.Promise;

// Connect to the mongoDB instance and log a message
// on success or failure
mongoose.connect(MONGO_URI);
mongoose.connection.once('open', () => console.log(`${chalk.blue(`  Connected to MongoLab instance `)}`));
mongoose.connection.on('error', error => console.log(`${chalk.yellow(`⚠  Error connecting to MongoLab: ` + error + ` ⚠`)}`));

app.use(cors());

// We pass the schema as an option to our expressGraphQL middleware
app.use('/graphql', expressGraphQL({
  schema,
  graphiql: true
}))

module.exports = app;

我的index.js(服务器端):

const app = require('./app');
const chalk = require('chalk');

const PORT = 8080;

app.listen(PORT, () => {
  console.log(`${chalk.green(`✔  Server started on http://localhost:${PORT} ✔`)}`);
});