Shih-Min Lee
Shih-Min Lee

Reputation: 9700

React starter kit communication with RESTful backend API service

https://github.com/kriasoft/react-starter-kit

I have a backend API server running and I am looking for a frontend framework. Then I came across this react-starter-kit that seems to be a good candidate.

My understanding is that I am dealing with react components one at a time. and I can put the all code logic such as API calls, DOM element changes....etc in componentDidMount() so there will be interaction between DOM and the logic. (am I right?)

import React, { PropTypes } from 'react'; // eslint-disable-line no-unused-vars
import styles from './ContactPage.less'; // eslint-disable-line no-unused-vars
import withStyles from '../../decorators/withStyles'; // eslint-disable-line no-unused-vars

@withStyles(styles)
class ContactPage {

  static contextTypes = {
    onSetTitle: PropTypes.func.isRequired
  };

  render() {
    let title = 'Contact Us';
    this.context.onSetTitle(title);
    return (
      <div className="ContactPage">
        <div className="ContactPage-container">
          <h1>{title}</h1>
          <p>...</p>
        </div>
      </div>
    );
  }

}

export default ContactPage;

This is the original code of the react component I am trying to hack. I tried to include "request" module so that I can make http requests.

var request = require('request');  // for backend API calls

componentDidMount() {
    request('https://www.google.com')
}

It didn't work. So what I am doing wrong here? Thanks.

The error message is very long, started with the following message.

ERROR in ./~/request/lib/har.js Module not found: Error: Cannot resolve module 'fs' in /Users/ssmlee04/Desktop/react-starter-kit/node_modules/request/lib @ ./~/request/lib/har.js 3:9-22

Upvotes: 1

Views: 3501

Answers (1)

Giuseppe Pes
Giuseppe Pes

Reputation: 7912

Request.js is a lib for Node. It is not meant to be used in the browser. That is why you are seeing the error module fs not found. fs is the file system module of node js.

Since you are already using ES6 I suggest to use fetch (https://fetch.spec.whatwg.org/) to make request to the remote server. It is already supported by chrome and firefox. To have compatibility with older browser you can use fetch polyfill from github. Here it is the link to the repo https://github.com/github/fetch.

Upvotes: 5

Related Questions