0

Ok so I have a very simple app with create-react-app. Now I'm using ExpressJS to handle API calls that I am making with the $.ajax() method inside of my react app within the componentWillMount() method.

So all the React front end has is a simple form with 1 input field and submit like so:

import React, { Component } from 'react';
import $ from 'jquery';
import './App.css';

class App extends Component {


  componentDidMount(){

      $('form').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
          url: '/api',
          type: 'post',
          data: $('form').serialize(),
          dataType: 'json',
          success: function(data) {
            console.log('successful ajax request made!');
          }
        });

      });
  }

  render() {
    return (
      <div className="App">
        <form method="POST">
          <input type="text" name="title" />
          <input id="submit" type="submit" />
        </form>
      </div>
      );
  }
}

export default App;

Now my express route look like this:

var express = require("express");
var router = express.Router();

router.post("/api", function(req, res, next){
    console.log(req.body);
});

module.exports = router;

THE PROBLEM

When running create-react-app with npm start it goes to localhost:3000 do to the Webpack local dev server and when I fire off my app.js in my server directory with node server/app.js is goes to localhost:3001 because they cannot run in the same port.

Because of this I cannot make proper API calls without getting an error showing that the POST request has failed.

So now the golden question is how can I make API calls from a local server on 2 different ports?

If you need any more info about my code i'd be more than happy to post it. Help is greatly appreciated, thank you!

1
  • As a side note to my answer, I suggest you to change jQuery (because its big size) for the package fetch because it is an standardized API used to try to unify the XMLHttpRequest calls in modern browsers, with polyfills for support of older browsers. Commented Jul 5, 2017 at 19:22

3 Answers 3

1

Add this line in your existing client Package.json file

"proxy": {
   "/api/*": {
      "target": "http://localhost:3001"
   }
}

I am considering that your front end runs on PORT 3000 and you are making a request to PORT 3001 where your express server relies. After making the changes, kill the existing front end server and restart it. Hot reloading wont update Package.json file. Now all your request to /api/ will be directly routed to your PORT 3001

Sign up to request clarification or add additional context in comments.

1 Comment

This solved my problem where I had the create-react-app dev server + api server running with only "proxy:"http://localhost:3001" running. This led to a 404 but only on Firefox for http://localhost:3001/sock-js/node/. Great solution you helped me a lot. Now my dev server refreshes fine on Firefox again and I have my API working.
0

If I understood you correctly, your front-end is running on localhost:3000 whereas backend running on local:3001, so you're looking for a solution to make request from front-end to back-end serving on 2 different ports? If that so I believe you need to call your backend using the baseUrl, http:localhost:3001/api_call_here

        $.ajax({
          url: 'http:localhost:3001/api',
          type: 'post',
          data: $('form').serialize(),
          dataType: 'json',
          success: function(data) {
            console.log('successful ajax request made!');
          }
        });

2 Comments

Thank you so much for the reply, iv'e tried that and for some reason the only thing that I get in the backend console is an empty object. So I don't get the serialized form data and I don't get the message within my ajax success method that says "successful ajax request made!". So my guess is the post request did not successfully go through. No I do not get any errors but I don't get the data to log on my backend console like I had hoped. Any idea why the req.body isn't logging the data passed through?
I too guess the post request wasn't successful that's why the success callback isn't called, you can try providing error callback and log it to know what is the error. Alternatively, you can try the above request in any Rest client to log the error as well
0

You have to set up in your package.json this line:

"proxy": "http://localhost:PORT"

being PORT the port number you set up in your Express server.

Thus, Webpack local dev server knows which URL has to call to in order to reach your API run by Express.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.