0

i'm working on a web project that should provide restful post service with react framework.

there are a lot of consuming rest service example on internet.

however, i want to provide restful service.

I tried the following,

1- provide service from react framework. i see it is not possible.

2- provide service from express and binding it with react via proxy https://www.youtube.com/watch?v=v0t42xBIYIs

for this example, get method works but post method does not.

my express server like below.

const express = require('express');
const app = express();

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/api/customers', (req, res) => {

  res.json(req.body);
});


const port = 5000;

app.listen(port, () => `Server running on port ${port}`);

after that, , use proxy and react code like this

  componentDidMount()
  {

      fetch('/api/customers')
      .then(res => res.json())
      .then(customers => this.setState({customers}, () => console.log('Customers fetched...', customers)));

at that point i get the below error

customers.js:18 GET http://localhost:3000/api/vehicles 500 (Internal Server Error)

thank you for all advice.

i'm searching for best practice.

AhuraMazda
  • 460
  • 4
  • 22
  • What is `fetch` inside `fetch`? is it a typo? and url `lhost:3000` and endpoint `lhost:5000` are different and you may require cors library too. also you should check how to use fetch for post req. – Jai Feb 11 '20 at 08:37
  • 1
    It doesn't work because you're not making a POST request from React or defining a GET for that route in Express. – jonrsharpe Feb 11 '20 at 08:38
  • fetch inside fetch is typo while pasting to stackoverflow. 5000 is express port. 3000 is react client port. they are bound with proxy. – AhuraMazda Feb 11 '20 at 08:50
  • i don't want to do post request from react. i want to do it externally like postman. – AhuraMazda Feb 11 '20 at 08:52
  • ` web project that should provide restful post service with react framework` that is not react is built for. what is your requirement over this? – AZ_ Feb 11 '20 at 08:59
  • yeah i see that for first try. i m searching for the best practice. should i use express server for providing reset service or what ever else. final aim is that there is a list (customers ) contuniously changing via post request. i should show on reactjs. – AhuraMazda Feb 11 '20 at 09:27

4 Answers4

1

The result of a React application build are script bundles and html files (also can include source maps for debugging) commonly referred to as build artifacts.

The best practice is simple:
When Express is involved the React app should download the build artifacts and API responses from Express (commonly called backend in this scenario).

What happens when this is not followed:
1. React frontend server (typically webpack-dev-server) is used in production. This is not a good idea, webpack-dev-serveris meant to be used in development only.
2. Browser detects that JS code from the bundles downloaded from one server (frontend) attempts to call another server (backend) and triggers a security violation which is meant to improve security. People then use CORS HTTP headers (sent by backend) to make the backend tell browsers: "Don't worry about security and don't trigger security violations, I (the backend) has been hardened to such an extent that I don't care that some code downloaded not from me tries to access me". The browser complies and this results in security needlessly watered down.

When to proxy:
In development only. The webpack-dev-server is excellent for development with its support for Live Reloading, HMR etc. To keep those advantages the backend (Express) can and should serve as a reverse proxy for the frontend. E.g. when Express receives a request for a build artifact, it should download it from the frontend first and then use it to send the response back. This ensures CORS issues do not arise.

winwiz1
  • 2,906
  • 11
  • 24
0

Two issues stand out

Post vs Get

You're serving your api from a post endpoint. Change it to get.

app.get('/api/customers', (req, res) => {res.json(vehicleList);});

fetch

In the UI, it shows you are fetching from localhost:3000 when you should be fetching from localhost:5000. I assume your proxy is rerouting 3000 -> 5000 so hopefully this isn't an issue. I would however doublecheck and try hitting the localhost:3000/api/customers url (copy and paste that into the url bar) and see if you see your json.

Also

It is certainly possible to have express serve the static react bundle from a the same base url as your api. e.g.

app.use('/', express.static('public'));
app.post('/api/customers', (req, res) => {
  res.json(vehicleList);
});
Onescriptkid
  • 182
  • 6
  • i m sorry for vehicleList tag. it should be "req.body". if i change it to get, i cannot get new customers list via postman. – AhuraMazda Feb 11 '20 at 09:29
0

Actually, I think you didn't focus that both are running on two different ports like your server is running on Port:5000 and react project port:3000 so just add "proxy":http://localhost:5000

//server.js  (node file)***

app.get('/api/customers', (req, res) => {
  const customers = [
    {id: 1, Name: 'Rohan', email: 'r@gmail.com'},
    {id: 2, Name: 'Rohan', email: 'r@gmail.com'}
  ];

  res.json(customers);
});

const port = 5000;

app.listen(port, () => `Server running on port ${port}`)

// React Script***

class Customers extends Component {
  constructor() {
    super();
    this.state = {
      customers: []
    };
  }

  componentDidMount() {
    fetch('/api/customers')
      .then(res => res.json())
      .then(customers => this.setState({customers}, () => console.log('Customers fetched...', customers)));
  }
Vijay Gehlot
  • 80
  • 1
  • 10
  • i said that get method works. problem is post method. i have dynamically changing customers array. some other project will post a customers list to my project. – AhuraMazda Feb 11 '20 at 12:33
0

i think there is no method for pushing data from server to client in a convensional way.

there is a good subject to push data from server to client. you may want to see that.

WebSocket vs ServerSentEvents

AhuraMazda
  • 460
  • 4
  • 22