How to make proxy point to port 3001

#1

I have server created with node/express that return these data from url: http://localhost:3001/api/users

[{"id":1,"username":"frank"},{"id":2,"username":"lowi"}]

This is the server code:

const express = require('express');
const app = express();
const proxy = require('http-proxy-middleware');

app.use(proxy('/api', { target: 'http://localhost:3001/' }));

app.get('/api/users', (req, res) => {
  res.json([
    {
      id: 1,
      username: 'frank'
    },
    {
      id: 2,
      username: 'lowi'
    }
  ])
});

app.get('/api/cars', (req, res) => {
  res.json([
    {
      id: 1,
      brand: 'bmw'
    },
    {
      id: 2,
      brand: 'nissan'
    }
  ])
});

const port = process.env.port || 3001;
app.listen(port);

but when I try to access these data with axios from the client I get error

GET http://localhost:3000/api/users 404 (Not Found)

Here is the client code:

import React, { Component } from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';

class App extends Component {

  componentWillMount() {
    axios.get('/api/users')
    .then(res => {
      console.log(res.data);
    });
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;
#2

Found the solution. According to documentation here (https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development)

I must set the proxy in file called setupProxy.js under /src folder in the client app !!!

1 Like