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

时间:2017-07-08 17:57:40

标签: express react-native react-fullstack

我使用React Native制作了一个UI,以及一个Cheerio.js刮刀(每天使用Cron Job激活一次)我会用来从网上抓取某些数据,因此它可以在UI中渲染。但是,我不知道如何链接他们两个。

我很确定我可以使用Express(我最适合后端)这样做,但有人可以告诉我我需要做什么才能将我的前端连接到后端吗?

以防万一,我是一名初级开发者(前端比后端更好)所以请保持简单的答案。即使你的答案更具概念性,而不是基于代码,我真的很感激。

2 个答案:

答案 0 :(得分:3)

API

我很高兴使用GraphQL作为REST的替代方案。但是,有很多方法可以通过api连接。您的客户端需要指向运行服务器的链接,并且您的服务器需要启用它。

教程

我想我无法解释它比本教程更好(在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} ✔`)}`);
});

答案 1 :(得分:1)

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