P
P
Praud2017-05-27 23:03:00
JavaScript
Praud, 2017-05-27 23:03:00

How to link create-react-app with back-end server?

Hello everyone, I’ve been sitting for 3 hours and I can’t connect the React application with the server on node (express)
In the documentation they write to register proxy in package.json.

"name": "marmelad",
  "version": "0.1.0",
  "private": true,
  "proxy": "http://localhost:3001/",

And so he did.
Here is my ajax
import axios from 'axios';

export const userLoginRequest = (data) => dispatch => {
      // return axios.post('/api/auth', data);
      return fetch('/api/auth', {
            method: 'POST',
            headers: {
               'Content-Type': 'text/html' 
            },
            body: data
      })
}

I used axios, but I'm already trying with fetch, so in the documentation.
Requests still go to localhost:3000 instead of 3001.
Everything is transparent on the server side
import express from 'express';
import bodyParser from 'body-parser';
// import cors from 'cors';

// import users from './routes/users';
import auth from './routes/auth';

const app = express();

app.use(bodyParser.json());

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
})

app.set('port', (process.env.PORT || 3001));

// Express only serves static assets in production
if (process.env.NODE_ENV === 'production') {
  app.use(express.static('client/build'));
}

app.use('/api/auth', auth);

app.listen(app.get('port'), () => {
  console.log(`Find the server at: http://localhost:${app.get('port')}/`);
});

import express from 'express';

let router = express.Router();

router.post('/api/auth', (req, res) => {
    console.log(req.body);
})

export default router;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Fadi Haj, 2017-05-28
@fdhaj

Apparently `proxy` is a setting for npm. You need to use your own configuration or read from package.json and substitute when requested.

P
Praud, 2017-05-28
@Praud

app.use('/api/auth', auth);
It's just here
. That was the problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question