Getting Blank page on localhost:3000 while using npm along with reactjs - node.js

enter image description here
var express = require ('express');
//create our app
var app = express();
app.use(express.static('public'));
app.listen(3000,function(){
console.log('Sever is up on port 3000');
});
This is code of Server.js file.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.js"></script>
</head>
<body>
<script type="text/babel" src="app.jsx"></script>
</body>
</html>
Code of index.html file
var Greeter = React.createClass({
render: function(){
return(
<div>
<h1> Howdy! </h1>
</div>
);
}
});
ReactDOM.render(
<Greeter/>,
document.getElementbyId('app')
);
Code of app.jsx file
where is error? i don't find any error.
But when I am opening http://localhost:3000, I am getting a blank page.
Am using Windows 10 and node -v 6.9.1
Any help would be highly appreciated! Thanks.

You forgot to add html element with id='app', Include this in html file, it will work.
<div id="app"></div>
There is an error in this part:
ReactDOM.render(
<Greeter/>,
document.getElementbyId('app')
);
check the spelling of getElementbyId, instead of that put this getElementById.

Try babel 5.8.23.
You forgot to put in the app HTML element.
<div id="app"></div>
Also, there's a typo in getElementById. The B should be caps.
ReactDOM.render(
<Greeter/>,
document.getElementById('app')
);

Please update a Div with id as app since React is not able find an Div with id app
<div id="app"/>

continued to the answer by #MayankShukla. Try adding script for babel transpiler to transform jsx code, include this reference:
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.19.0/babel.min.js"></script>

Related

Express only serving css file in main page

I am learning node and using expressjs the problem is that the css file is only working on the main page and not any other page following is the code for the app:
var express = require("express");
var app = express();
// assets
app.use(express.static("public"));
// simple file testing
app.get("/anything/:stuff", function(req, res){
var stuff = req.params.stuff;
res.render("love.ejs", {stuff: stuff});
});
// posts page
var books = [
{title:"Harry Potter",author:"JK Rowling",editions:7},
{title:"Peere Kamil",author:"Humaira Saeed",editions:4},
{title:"Mushaf",author:"Abdullah khan",editions:2}
];
app.get("/books", function(req, res){
res.render("books.ejs",{books:books});
});
app.listen(3000, process.env.IP, function(){
console.log("Serving Now!");
});
The following is the code for the page where it is not working.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="app.css" />
<title>demo app</title>
</head>
<body>
<h1>You fell in love with : <%= stuff %> </h1>
<%
if(stuff.toUpperCase() === "WAQAS"){ %>
<P>GOOD CHOICE HE IS THE BEST</p>
<% } %>
<p>P.S This is the love.ejs file</p>
</body>
</html>
The file is under public directory.
Use an absolute URL for the CSS file, so the browser doesn't look for it relative to the current URL:
<link rel="stylesheet" href="/app.css" />
Explanation: say that you open the URL /anything/helloworld in your browser. When your HTML contains just app.css, without the leading slash in front of it, the browser will try and load /anything/app.css (because without that slash it's relative to the current URL), which doesn't point to your CSS file.
When you add the leading slash, express.static will be able to find the CSS file in public/.

NodeJS Express | ReactJS component causes timeout error while testing a view using Mocha and ZombieJS

I have added to my Node ExpressJS app some components in ReactJS. Since I introduced these components, my tests are failing due to timeout error.
My test suites is including mocha, zombie, chai and sinon, but the first two are enough to reproduce the error.
This is the test:
// tests/home-tests.js
process.env.NODE_ENV = 'test';
var app = require('../index.js');
var Browser = require('zombie');
describe('Homepage Tests', function() {
before(function(){
server = app.listen(3002);
browser = new Browser({ site: 'http://localhost:3002' });
})
it('should render title', function(done){
browser.visit('/', function() {
browser.assert.text('h1', 'A test page for ReactJS');
done();
})
});
after(function(done) {
server.close(done);
});
});
This is the layout:
// views/layouts/main.handlebars
<!doctype html>
<!--[if IE 8]> <html class="ie ie8"> <![endif]-->
<!--[if IE 9]> <html class="ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Zombie ReactJS Test!</title>
{{{_sections.page_stylesheets}}}
</head>
<body>
{{{body}}}
{{{_sections.page_javascripts}}}
</body>
</html>
This is the view I want to test:
<h1>A test page for ReactJS</h1>
<div id="example"></div>
{{#section 'page_stylesheets'}}
<!-- ReactJS -->
<script src="https://npmcdn.com/react#15.3.1/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom#15.3.1/dist/react-dom.js"></script>
<script src="https://npmcdn.com/babel-core#5.8.38/browser.min.js"></script>
{{/section}}
{{#section 'page_javascripts'}}
<script type="text/babel">
ReactDOM.render(
<p>Hello, world!</p>,
document.getElementById('example')
);
</script>
{{/section}}
I have reproduced the error in this small repo.
It seems that it could be easily fixed with a timeout like it follows:
// tests/home-tests.js
// ...
it('should render title', function(done){
this.timeout(5000);
browser.visit('/', function() {
browser.assert.text('h1', 'A test page for ReactJS');
done();
})
});
However, this doesn't appear to be the most suitable solution. In particular, would you be able to suggest a way to run test only after the page is fully loaded (without timeouts to be set)?
Thank you in advance

Node.js jsdom set document root

I am trying to load local javascripts with jsdom.
Now I am wondering how I can make jsdom loading the javascripts from "__dirname/../public".
Can someone help me?
My current code is:
var fs = require('fs');
var jsdom = require('jsdom');
jsdom.defaultDocumentFeatures = {
FetchExternalResources: ["script"],
ProcessExternalResources: ["script"],
MutationEvents : '2.0',
QuerySelector : false
};
exports.test = function(req, res) {
var html = fs.readFileSync(__dirname+'/../public/html/lame.html');
var document = jsdom.jsdom(html, null, {documentRoot: __dirname+'/../public/'});
var window = document.createWindow();
window.addEventListener('load', function () {
//window.$('script').remove();
//window.$('[id]').removeAttr('id');
res.send(window.document.innerHTML);
window.close();
});
}
The simple HTML page is:
<html>
<head>
<title id="title">bum</title>
<script type="text/javascript" src="/javascripts/jquery.min.js"></script>
<script type="text/javascript" src="/javascripts/stuff.js"></script>
</head>
<body>
<h1>hello world</h1>
<h2 id="bam">XXX</h2>
</body>
</html>
I've run into the same issue and got it to work. Try these, in order:
documentRoot is not documented. The option which is documented is url. So replace documentRoot with url.
If the above is not enough, then add a base element. I've set my templates like this:
<head>
<base href="#BASE#"></base>
<!-- ... -->
</head>
where #BASE# is replaced with the same value as the one passed to url.
The solutions above are extracted from actual code in use in a test suite.

Testing NodeJS with Mocha - "Require is not defined"

I've been having trouble setting up a test framework for a NodeJS + Backbone app with the constant "require is not defined" error. I finally got it working using an in-browser test framework which picks up all of the dependencies I need and running a test.js file.
Currently, I'm only doing basic testing of my Backbone models, views, and collections. Now, I want to add in API testing but I'm back to the same "require is not defined" error. What is causing this? It's clear that I'm missing something fundamental here. I just want to add:
var request = require('supertest')
, express = require('express');
var app = express();
Snippet of test.js:
describe('Application', function(){
it("creates a global variable for the namespace", function() {
should.exist(App);
})
});
describe('Models', function() {
describe('SearchFormModel', function() {
beforeEach(function() {
this.SearchFormModel = new App.Model.SearchFormModel();
this.defaultFields = this.SearchFormModel.attributes;
})
it("created a SearchFormModel", function() {
should.exist(this.SearchFormModel);
})
it("should have 7 default fields", function() {
Object.keys(this.SearchFormModel).length.should.equal(7);
})
it("should default all fields to empty string", function() {
for (var key in this.defaultFields) {
this.defaultFields[key].should.equal("");
}
})
});
});
test-runner.html:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Title & Meta -->
<title>Frontend tests</title>
<meta charset="utf-8">
<!-- Stylesheets -->
<link rel="stylesheet" href="../node_modules/mocha/mocha.css">
</head>
<body>
<div id="mocha"></div>
<!-- Testing Libraries -->
<script src="../node_modules/mocha/mocha.js"></script>
<script src="../node_modules/chai/chai.js"></script>
<script>
// Use the expect version of chai assertions - http://chaijs.com/api/bdd
var should = chai.should();
// Tell mocha we want TDD syntax
mocha.setup('tdd');
</script>
<!-- Libs -->
<script src="../public/lib/jquery-1.8.2.min.js"></script>
<script src="../public/lib/underscore-min.js"></script>
<script src="../public/lib/backbone-min.js"></script>
<script src="../public/lib/bootstrap.min.js"></script>
<script src="../public/lib/highcharts.js"></script>
<script src="../public/lib/bootstrap-datepicker.js"></script>
<script src="../public/js/modules/exporting.js"></script>
<!-- Source files -->
<script src="../public/js/namespace.js"></script>
<script src="../public/js/jst.js"></script>
<script src="../public/js/utils.js"></script>
<script src="../public/js/models/models.js"></script>
<script src="../public/js/models/search.js"></script>
<script src="../public/js/models/plot.js"></script>
<script src="../public/js/models/search_result.js"></script>
<script src="../public/js/views/header.js"></script>
<script src="../public/js/views/plot.js"></script>
<script src="../public/js/views/list.js"></script>
<script src="../public/js/views/search.js"></script>
<script src="../public/js/router.js"></script>
<script src="../public/js/app.js"></script>
<!-- Test -->
<script src="test.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
require and commonjs only works in Node.js
If you run Browser test, then you need to code it like you'll run it in the browser. Also note that Unit Test should be done in isolation, you shouldn't need to load you app server (express) to run your test.
I'd like to point you to an easy solution from there, but there's just too many choices. Very basically, you should start running browser test in the browser by loading an html file.
Then, you'll want to automatize this and run browser test from the terminal. That's when you want to run test in PhantomJs and the likes and output browser results on the terminal. Around this, you can checkout Karma and Testem who're two browser test runner (remember here Mocha alone won't run browser test via command line).
As you're using Backbone, you might be interested in the Backbone-Boilerplate Karma + Grunt test setup as a starting point. See more on this here: https://github.com/backbone-boilerplate/backbone-boilerplate

Can't get stylesheet to work with ejs for node.js

I'm trying to make a simple server with node, express and ejs for the template. I've gotten the server to point to the page, load it, and am even able to generate other bits of code with the include statement. However for some reason the style sheet will not load.
app.js
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
fs = require('fs');
var PORT = 8080;
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.render('board.ejs', {
title: "anything I want",
taco: "hello world",
something: "foo bar",
layout: false
});
});
app.listen(PORT);
console.log("Server working");
The ejs file is in a directory views/board.ejs
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='../styles/style.css' />
</head>
<body >
<h1> <%= taco %> </h1>
<p> <%= something %> </p>
</body>
</html>
and style.css is in a styles/style.css directory relative to app.js
p {
color:red;
}
I've tried every path that I can conceive of for the href of the link including relative to where my localhost points relative to app.js relative to board.ejs and even just style.css but none seem to work. Any suggestions are greatly appreciated.
Declare a static directory:
app.use(express.static(__dirname + '/public'));
<link rel='stylesheet' href='/style.css' />
in app.js:
you must first declare static directory
app.use("/styles",express.static(__dirname + "/styles"));
in ejs file :
<link rel='stylesheet' href='/styles/style.css' />
Recently I was working with this same thing and my CSS was not working. Finally, I get the trick. My static path was like below,
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const staticDirectory = express.static(publicDirectoryPath);
app.use(staticDirectory);
and my folder structure was like
The trick is that express access only defined static path, in my case CSS was outside of public so it was not working and suddenly I move CSS folder inside my public folder and that's it. Works beautifully.
Above example was for only one static path. For multiple static path you can use the code in the below
const app = express();
const publicDirectoryPath = path.join(__dirname, '../src/public');
const cssDirectoryPath = path.join(__dirname, '../src/css');
const staticDirectory = express.static(publicDirectoryPath);
const cssDirectory = express.static(cssDirectoryPath);
app.use(staticDirectory);
app.use('/css/',cssDirectory);
And my generic HTML file is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
<link rel="stylesheet" href="../css/styles.css">
</head>
<body>
<h1>this is index page</h1>
</body>
</html>
To set the entry point for your application dependancies like css, img etc add below line into your server.js (or which ever being used).
app.use(express.static(__dirname + '/'))
This tells to get css files from current directory where server.js is present. Accordingly you can define relative path of css in html file.
With Express 4, you can easily set this up by using the following within your app.js file.
app.use('/static', express.static(path.join(__dirname,'pub')));
Place this early in your file, after you created your require constants, and declared your express app.
Its declaring a static directory, with the help of the path object, allowing you to have a place where all of your front-end resources are available. It's also giving it a virtual directory name (/static) that can be used on the front of the site, instead of the physical name you see within your project (/pub).
In your template you can do something like this in your head
<link rel="stylesheet" href="/static/css_bundle.css"/>

Resources