2

I'm trying to implement a payments system in my ReactJS app that requires server-side code.

I have several questions:

  • How do you connect a ReactJS app so it can communicate with server-side code?
  • How would you set up a function in the server-side code?
  • How would you call that function from a component in a ReactJS app?

For reference, I'm trying to integrate Stripe subscriptions. They give server-side code examples for Node, PHP, etc.

FYI: I am not trying to set up server-side rendering. When you search for server-side code in reference to ReactJS, that's just about all that comes up.

EDIT: I'm particularly interested in a NodeJS solution. I'm also using Webpack.

tsteve
  • 549
  • 1
  • 7
  • 16

1 Answers1

2

Just in case, it is helpful to you... I have a React UI that triggers video processing on a Django backend (I mainly use GraphQL through Apollo Client to trigger my server side functions and REST framework when file transfers are involved). Is REST an option for you?

The middleware I use for file transfers for example:

const SERVER_URL = process.env.SERVER_URL;

const fileTransferApi = (payload) => {
  const { authenticated, token, endpoint, body, contentType, method } = payload;

  let config = {};

  if (authenticated) {
    if (token) {
      config = {
        method,
        headers: {
          'Content-Type': contentType,
          Authorization: `Bearer ${token}`
        },
        body
      };
    } else {
      throw new Error('No token saved!');
    }
  }

  return fetch(`${SERVER_URL}/api/rest/v1/${endpoint}`, config)
    .then((response) =>
      response.text().then((text) => ({ text, response }))
    ).then(({ text, response }) => {
      if (!response.ok) {
        return Promise.reject(text);
      }
      return text;
    }).catch((err) => console.log(err));
};


export const FILE_TRANSFER_API = Symbol('FILE_TRANSFER_API');

export default () => (next) => (action) => {
  const fileTransferApiAction = action[FILE_TRANSFER_API];

  if (typeof fileTransferApiAction === 'undefined') {
    return next(action);
  }

  const { payload, types } = fileTransferApiAction;

  const [, successType, errorType] = types;

  return fileTransferApi(payload).then(
    (response) =>
      next({
        type: successType,
        payload: {
          text: response,
          message: 'ok'
        }
      }),
    (error) => next({
      type: errorType,
      payload: {
        error: error.message || 'There was an error.'
      }
    })
  );
};

My store (I use Redux):

import { createStore, compose, applyMiddleware } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import ReduxThunk from 'redux-thunk';
import ApolloClientSingleton from '../network/apollo-client-singleton';
import fileTransferApi from '../middlewares/fileTransferApi';

import reducer from './reducers';

export default class Store {
  constructor(history, initialState = {}) {
    this.data = createStore(
      reducer,
      initialState,
      compose(
        applyMiddleware(
          fileTransferApi,
          ReduxThunk.withExtraArgument(ApolloClientSingleton),
          routerMiddleware(history),
          ApolloClientSingleton.middleware()
        ),
        typeof window === 'object' && typeof window.devToolsExtension !== 'undefined'
          ? window.devToolsExtension() : (f) => f
      )
    );
  }
}

In my actions:

export const windowsDownload = (authenticated, token) => ({
  [FILE_TRANSFER_API]: {
    types: [WINDOW_DOWNLOAD_REQUEST, WINDOW_DOWNLOAD_SUCCESS, WINDOW_DOWNLOAD_FAILURE],
    payload: {
      endpoint: 'file_transfer/download/windows',
      contentType: 'text/csv',
      method: 'get',
      body: null,
      authenticated,
      token
    }
  }
});

This REST setup enables me to send requests (POST video, GET csv...) from my React UI to my Django server. Can't you set up some REST calls between your app and your server?

Community
  • 1
  • 1
vwrobel
  • 1,706
  • 15
  • 25
  • I'm working on an implementation similar to your answer -- I don't nearly have all the kinks worked out yet, but I think it's safe to call your answer the correct one. A REST solution seems to be the way to go. The piece I've been missing all along is the server piece. I've just got to get the server set up so I can make calls to it, and then your solution should work just fine. Thanks! – tsteve Nov 29 '16 at 04:29