I'm trying to make initial connection between my node js with apache2 web server backend to my React frontend. I'm newbie at all of this and trying to make it work on local machine before deployment. I read about CORS and solve an issue with access origin headers with it, but I can't understand what am I missing here.
the server runs and listening to port 3000 the frontend on port 3001
my frontend code is:
import React from 'react';
import axios from 'axios';
import logo from './logo.svg';
import './App.css';
export default class App extends React.Component {
state = {
persons: []
}
componentDidMount() {
axios.get(`/ping`, {
headers: {
"Access-Control-Allow-Origin": "*"
}
})
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
render() {
return (
<h1>dfdfdfdfdf{this.state.persons}</h1>
)
}
}
And My Backend code is:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cors = require('cors');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
const hostname = '127.0.0.1';
const port = 3000;
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.use(express.static(path.join(__dirname, 'build')))
app.get('/ping', (req, res) => {
return res.send('pong')
})
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'))
})
app.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
module.exports = app;
I keep getting the errors:
Failed to load resource: the server responded with a status of 404 (Not Found) 0.chunk.js:779 Unhandled Promise Rejection: Error: Request failed with status code 404 (anonymous function) (0.chunk.js:779) promiseReactionJob
Aucun commentaire:
Enregistrer un commentaire