Express app not rendering my react components - node.js

I'm building a Express app using React. I start my server, go to localhost and I see a blank page, when I check the developer tools on chrome it shows me that my js file is plain HTML. Why is that?
This is my server.js:
var express = require('express');
var app = express();
var port = process.env.NODE_ENV || 3000;
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});
app.listen(port, function() {
console.log('Listening to http://localhost:' + port);
});
This is my app.js:
var React = require('react'),
ReactDOM = require('react-dom');
var App = React.createClass({displayName: "App",
render () {
return (
React.createElement("h1", null, "Hello World!!!!!")
)
}
});
ReactDOM.render(React.createElement(App, null), document.getElementById('main-app'));
My index.html:
<body>
<div id="main-app"></div>
</body>
<script src="public/assets/dist/javascripts/app.js"></script>
This is what I see on developer tools:
image

The problem is that whatever file you are requesting to your server you are always returning index.html.
So when you go to http://localhost:3000/ you get index.html
The problem is that your index.html then requests public/assets/dist/javascripts/app.js but you still return index.html as if it was app.js.
You need to update your route so it returns the file that was requested.
I think adding this to your server.js might fix it.
app.use(express.static(__dirname + '/public'));
Instead of
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});

Related

Is index.html name is predefined in Express?

index.html login.html app.js
I have two files named index.html & login.html,whenever I start server with index.html file it load ,but when I route to the login then login.html don't work,so then after I interchange code in files then login.html files load but as index.html
Try this code and see if it works, not much information is provided in the question.
Maybe show your code.
var express = require('express');
var PORT = 3400;
var path = require('path');
var app = express();
app.get('/login',function(req,res){
req.sendFile(path.join(__dirname + '/login.html'));
})
app.get('/index',function(req,res){
req.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(PORT,function(){
console.log('Serving on PORT' + PORT);
})

Why is expressjs returning the error "Cannot GET /" in the browser from code below?

Using the code below with nodejs, expressjs, socket io and pug
the browser response is Cannot GET /
Have had same or similar response to get in other code
Have index.pug file in root and views (just in case)
Tried various permutations such as "/", "./", "/views", "/views" etc
const express = require('express')
const socket = require('socket.io')
const app = express();
app.set('view engine','pug')
app.get("./", function(req, res){
res.render("home");
})
const runServer = app.listen(8585, ()=> console.log('server is running at 1 27.0.0.1:8585'))
Server runs at localhost:8585 in terminal (GIT bash) OK
Expected result: "Home" page in browser
Actual result: the browser when "./" response is Cannot GET /
If using "/" (vs "./") then terminal and browser either crash or respond with blank
Have you got a route for GET / set?
router.route('/').get(function (req, res) {
res.send('app successfully running.')
})
If you are rendering 'home' then why do you have index.pug inside views. You should have home.pug inside views folder. I tried the below code and it worked.
Folder structure:
- server.js
- views/home.pug
Code -
const express = require('express');
const app = express();
app.set('view engine','pug')
app.get("/", function(req, res){
res.render("home");
})
const runServer = app.listen(8585, ()=> console.log('server is running at 1 27.0.0.1:8585'))

Cannot GET / Express ERROR

I am learning Mean.js stack, and try to build an app. I have installed Express, and it works. When I tried to configure my static file ( html, js, images, etc.), then things broke.
Here are my files:
server.js
var express = require('express');
var app = express();
app.use(express.static(__dirname + "public"));
app.listen(3000);
console.log('Server running on port 3000');
My html file is very simple :
<!DOCTYPE>
<html>
<head>
<title>Contact List App</title>
</head>
<body>
<h1>Contact List App</h1>
</body>
</html>
So when I start the server : node server.js, and then I type http://localhost:3000/ in the browser, I get the "Cannot Get" error.
Where is the problem?
__dirname doesn't have a trailing slash, so you need to provide one yourself when building the static root:
app.use(express.static(__dirname + "/public"));
^ this needs to be there
You need to make sure the route exists. Also, it is a better practice to use path for joining strings. Also, make sure the directory public exists and the file index.html is inside that folder.
var path = require('path');
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index.html');
});
app.listen(3000);
console.log('Server running on port 3000');

how to send data to client with expressJS

How would I go into retrieving data from expressJS? That is without it getting overwritten, or redirecting a user.
<html>
<body>
<h1>Retrieved data</h1>
</body>
</html>
for example how would i go into adding it if the server side looks like this?
var express = require("express");
var app = express();
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
//how do i add data to the <h1> tag
});
app.listen(10022, function () {
console.log("server is up");
});
You wouldn't be able to do it with a .html file. You'd need an EJS file. The markup for that would look like this.
<html>
<body>
<h1>Retrieved <%= data %></h1>
</body>
</html>
Then you'll need the ejs module. Run the following NPM command.
npm install ejs
So change your index.html to index.ejs, make sure it's in a directory named views, and then modify your server side code to this.
var express = require("express");
var app = express();
app.set("view engine", "ejs");
app.get("/", function (req, res) {
res.render("index", {data: 'This is the data'});
});
app.listen(10022, function () {
console.log("server is up");
});
EJS is a templating language that converts to HTML, taking the data object you've passed in through your render method, rendering it server side, and then sending it to the browser.

Nodejs & Angularjs, Clean urls

How do I setup node/angular to have the index.html/app run at example.com rather than example.com/app/index.html#/home
I tried putting the index.html at the root of the node server but that still leaves the url as example.com/index.html#/home
What you need is to enable html5mode. It's documentation and considerations can be found here.
Here's an example taken from Brian Ford:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives']).
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
// configure $routeProvider, then...
$locationProvider.html5Mode(true);
}
]);
The angular-ui framework has example configuration for wiring this up to express.js:
var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendfile('index.html', { root: __dirname });
});
app.listen(3006); //the port you want to use
In Brian's article, you don't have to manually map the static asset folders because his example delivers the single index.html, maps partials to /partials/:name, then interacts with /api/*
If you are using Yoeman, or grunt build on your NODEJS server.
You can simple add new file server.js into root folder, and if your app folder is inside and your root folder.
var express = require('express');
var app = express();
app.use(express.static(__dirname + "/app"));
app.all('*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('/app/index.html', { root: __dirname });
});
var port = 1337;
app.listen(port); //the port you want to use
console.log('Server running at localhost:' + port);
And make sure you have enabled HTML5 mode inside your AngularJs config
angular.module('yourApp')
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/some', {
templateUrl: '../templates/some.html'
})
.otherwise({redirectTo: '/'});
//enabling HTML5 mode
$locationProvider.html5Mode(true);
}
]);

Resources