Does not load the component in react. error in http: // localhost: 3000 / shows the message on the Can not GET page / when trying to load the React component

3

file: server.js

const express = require('express');

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

    const app = express();
app.use(express.static(__dirname + '/public'));

    app.use(express.static(__dirname + '/public'));
app.listen(3000, function () {

    app.listen(3000, function () {
    console.log('server on port 3000');

        console.log('server on port 3000');
});

    });

file: index.jsx


import React,{Component} from 'react' import {render} from 'react-dom';

class Prueba extends Component{ render(){ <h1>Plantilla React</h1> }} render(< Prueba/>,document.getElementById('app'));
    
asked by Developer 09.08.2017 в 01:47
source

3 answers

-1

Add the return , including the following line

app.get('/*', function(req, res, next) {
   res.sendFile('index.html', { root: __dirname });
});

Restart the computer, compile again by npm install react react-dom --save , run the server again and everything works perfect!

    
answered by 09.08.2017 / 19:29
source
2

First problem

At no time are you mapping a route to render the HTML. You should map every request GET to render the index. For that use the wilcard all (*):

const express = require('express');

const app = express();
app.use(express.static(__dirname + '/public'));
const root = <>; // directorio en donde está el index
app.get('*', (req, res) => res.sendFile('index.html', { root }));
app.liste(3000);

Second problem

The render method must return an element; you are not returning anything:

render() {
  return (
    <h1>Hola mundo</h1>
  );
}
    
answered by 09.08.2017 в 03:13
0

The problem is not in React, but in express. You have not defined a route to attend the requests that arrive at the root.

Here modify your file to include a function that will send the file index.html to all the request you receive.

file: server.js

const express = require('express'); 
const app = express(); 
app.use(express.static(__dirname + '/public')); 

app.get('/*', function(req, res, next) {
   res.sendFile('index.html', { root: __dirname });
});

app.listen(3000, function () {
    console.log('server on port 3000');
});

Assuming there is a index.html file at the same level as server:

<div id="app"> <!-- la plantilla react debería aparecer aqui --> </div>

Make sure that your index.html has an element with id="app", since that is where you are indicating to react to perform the Render, with document.getElementById('app')

    
answered by 09.08.2017 в 02:56