Answer the question
In order to leave comments, you need to log in
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/",
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
})
}
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
Apparently `proxy` is a setting for npm. You need to use your own configuration or read from package.json and substitute when requested.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question