I am just trying out node js and angular js. here is my node code:
var http = require('http');
var fs = require('fs');
var sys = require('sys');
http.createServer(function(req, res){
fs.readFile('angularjsex.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
}).listen(8000);
The angularjsex.html file:
<html ng-app>
<head>
<script type="text/javascript" src="angular.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}!</h1>
</div>
</body>
</html>
The angular js just does not work. Am i missing something?
You are returning the contents of the file angularjsex.html for every request. In your HTML file, there's a reference to angular.js that the browser will try to load from your server, and that request will get the same (HTML!) contents.
For a solution that works with your current server app, replace this:
<script type="text/javascript" src="angular.js"></script>
With this:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
But I would suggest to start using Express, in which case you can leave the HTML code as is if you change your server to this:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8000);
Create a directory public and place your angularjsex.html and angular.js files into it. To view the result, open http://localhost:8000/angularjsex.html in your browser.
To install Express:
npm install express
Related
I am new to node js and creating a simple application to query data stored in database(MySql) .So what i am doing is, I have created a database named stock and i am querying it using index.html to show it at get.html but after executing the get request i am not able to get the result.
Here is my app.js
const express=require('express');
const app=express();
const port= 5050;
const bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',(req,res)=>res.sendFile(__dirname + '/index.html'));
app.post('/get',function(req,res){
const mysql=require('mysql');
const con=mysql.createConnection({
host:"localhost",
user:"root",
password:"abc123",
database:"abc",
});
con.connect(function(err){
if(err) throw err;
console.log("Connected");
let sqlQuery='SELECT * FROM stock';
con.query(sqlQuery,(err,rows)=>{
if(err) throw err;
console.log('Data Received:-');
console.log(rows);
});
});
});
app.listen(port);
My Index.html:-
<!DOCTYPE html>
<html>
<head>
<title>My node js app</title>
</head>
<body>
<form action="/get" method="get">
<h1>Welcome to Stock manipulation</h1><br></br>
Select option<select>
<option value=0>Get</option></select>
<input type="submit" id="query" value="get Result">
</body>
</html>
And my get.html
<!DOCTYPE html>
<html>
<head>
<title>Get</title>
</head>
<body>
</body>
</html>
And here is the data stored at database
[ RowDataPacket { id: 1, type: 'BSE' },
RowDataPacket { id: 2, type: 'NSE' } ]
The error i am getting after Submitting the request is
What is your nodejs server saying? In your routes you typically want to return some data. for example in your case your /get route res.send(data). that way your front end can show the data received. Also looks like you need to change your form to be a post not a get (Edit: As Nikos M. mentioned).
If you are new to http requests I recommend downloading Postman to get used to testing your routes requests.
change
<form action="/get" method="get">
to
<form action="/get" method="post">
as you have defined the /get route (app.post('/get',function(req,res){/*..*/}))
to accept only post requests
Also in your /get route handler you should output something. Right now you do not output anything, only log to the node.js console
I am new to node js. i am trying to learn node js. My question is how can we create dynamic webpages using node js?
PHP
<html>
<body>
<?php .......... ?>
</body>
Like in php we can do this way. How can we do in node js.
First off you would start by installing the nodejs framework expressJS
sudo npm install express
For instance, let's say you want to create a form.
<html>
<body>
<head>
This is a simple form
</head>
<body>
<form action="/" method="POST">
<label for="firstName">First Name:</label>
<input name="firstName">
<br>
<label for="lastName">Last Name:</label>
<input name="lastName">
<br>
<button type="submit">send</button>
This what the server side part would look like
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false});
// Set EJS View Engine**
app.set('view engine','ejs');
// Set HTML engine**
app.engine('html', require('ejs').renderFile);
//set directory
app.set('views', __dirname + '/views');
//static folder
app.use(express.static('staticfolder'));
app.get('/form', function(req, res) {
//open form.html from the views directory
res.render('form');
});
app.post('/', urlencodedParser, function(req, res) {
//retrieve first and lastname
var firstName = req.body.firstName;
var lastName = req.body.lastName;
//open submitted.html after the user has submitted the form
res.render('submitted', {output: req.body.firstName});
});
app.listen(3000);
Page that will be displayed when user submits the form. It is called submitted.html in this case
<html>
<body>
<p> you have submitted the form </p>
<!--firstname entered by user-->
<p> your first name is <%= output %></p>
</body>
</html>
You need a template to dynamically change its content.
Step 1: Create a server with Express Node.JS Framework.
Step 2: Use EJS(Embedded JavaScript) to create a template.
Follow the instructions bellow:
https://shockoe.com/ideas/development/creating-dynamic-web-pages-ejs/
I wrote a very simple node.js server:
var express = require('express');
var cookieParser = require("cookie-parser");
var app = express();
app.use(cookieParser());
app.get('/', function(req, res){
res.sendFile(__dirname + "/hello.html");
});
app.get('/ajax', function(req, res) {
console.log('ajax request received');
console.log(req.cookies["username"])
})
app.listen(3000);
and a very simple client side html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> Hello World </h1>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
document.cookie = "username=John Doe";
$.ajax({
url: "http://127.0.0.1:3000/ajax",
}).done(function() {
alert('AJAX sent');
});
</script>
</body>
</html>
As you can understand, once the server runs and an end-user sends a get request to localhost:3000, the file 'hello.html' is served to client. The browser saves the cookie "username=John Doe" and sends AJAX request to endpoint localhost:3000/ajax. My intention is to read the content of the cookie in the server (I know that cookies are sent automatically from the client). However, req.cookies["username"] returns undefined.
Do you know why?
The problem is that I send a GET request to localhost:3000 and therefore the cookie is saved in the domain http://localhost. However, when I send an AJAX call to 127.0.0.1, the cookie is not sent because the browser treats 127.0.0.1 and localhost as different domains. Therefore, opening the browser with 127.0.0.1:3000 (instead of localhost:3000) can solve it.
I am learning nodejs with express platform. I generated an express project and there are 2 routing files that I edited. One routing file is "users.js" and it's supposed to render layou.hbs when '/users' is requested, the other is "index.js" and it's supposed to render "home.hbs" when '/' is requested. the problem is, when '/' is requested on the url box, i get layout.hbs output on the browser. What am i doing wrong?
Here is the code from the files.
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('home', {title:Express});
});
module.exports = router;
user.js
var express = require('express');
var router = express.Router();
router.get('/users', function(req, res, next) {
res.render('layout', {title:Express});
//res.send('respond with a resource');
});
module.exports = router;
Home.hbs
</!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>goodbye World</p>
</body>
</html>
layout.hbs
</!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p> Hello World!</p>
</body>
</html>
if i visit localhost:3000, I expect to see "goodbye world" but I see "hello world", what is wrong with this code? Thank you.
In both the files you are rendering 'home'. In line res.render('home', {title:Express});
In user.js do this:
res.render('layout', {title:Express});
Cheers:)
You should remember to require express-hbs and tell express to use that. Your main app.js or any other names you gave that file should look like this.
var http = require('http');
var express = require('express');
var hbs = require('express-hbs'); //load handlebars
var app = express();
// setup hbs view engine
app.set('view engine', 'hbs');
//location of your views folder
app.set('views', __dirname + '/views');
http.createServer(app).listen(3000);
Whatever template you render, it will be loaded as the body of your layout. For this to work, your layout should look like:
</!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
{{{body}}}
</body>
</html>
The actual body contents should go in the template you render
home.hbs
<p> Hello World!</p>
goodbye.hbs
<p> Goodbye World!</p>
So doing
res.render('home');
Would show "hello world" whereas rendering
res.render('goodbye');
Would display "Goodbye world"
If you wanted to use a different layout to wrap a given template, you can override the default:
res.render('other', {layout: 'other_layout'});
BTW, passing the variable "title" as
{title: Express}
Means nothing. The "Express" variable isn't declared. You should instead use a defined variable or pass a string literal
{title: 'Express'}
And, to have it displayed in the generated HTML, the layout would use it like this:
</!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
</head>
<body>
{{{body}}}
</body>
</html>
Please note the body part has 3 curly braces whereas the template vars use only 2.
at last time I have learn use AngularJS and NodeJs, but I have a few problems.
First:
I'd like loading.. for instance index.html or other file, now I do this manual and simplest how I can, but even then I have problem with type file which are include in index.html I receive:
Resource interpreted as Stylesheet but transferred with MIME type text/html:...
How can I correct this ?
below code.
'use strict';
var http = require('http');
var fs = require('fs');
var mysql = require('mysql');
var render = function(response, fileName, code, httpCode){
var code = code || 'utf8';
var httpCode = httpCode || 200;
fs.readFile(fileName, code, function(err, data){
if(err) { return console.log(err); }
response.writeHead(httpCode, {'Content-type': 'text/html; charset='+code});
response.write(data);
response.end();
});
};
http.createServer(function(req, res){
render(res, 'index.html');
}).listen(9999, '127.0.0.1');
console.log('Server running');
html:
<!doctype html> <html class="no-js"><head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type='text/css' href="styles/main.css">
</head><body></body></html>
Can I use nodejs server with gruntjs ? if yes, how I can do it ?
Do somebody know any tutorial only angular + node ? it's mean I know quite good angularJS, but I can't use it with nodeJS..
The problem is that your browser requested a css file and you returned a file with the MIME type text/html. You would have to handle all the possible types of files (js, html, txt, css, ...).
I would recommend you to use an existing module like express, which will save you a lot of time. After installing express, initalize a static file server by doing following:
server.use(express.static(__dirname + '/public'));
This is how my folder structure look like of Angular JS + Node JS (with Express JS)
ProjectTitle
|_app
|_bower_components
|_images
|_scripts
|_styles
|_views
|_index.html
|_favicon.ico
|_routes
|_test
|_.bowerrc
|_.jshintignore
|_.jshintrc
|_bower.json
|_Gruntfile.js
|_package.json
|_README.md
|_server.js
3 imp things to notice here
/app - contains angular static app including all its dependant styles, scripts & images
/app/script - angular javascript files
/server.js - node js web server code, here is sample code
var express = require('express'),
http = require('http'),
path = require('path');
var app = express();
// all environments
app.configure(function() {
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(express.static(path.join(__dirname, 'app'))); // here you are mentioning which directory should be static directory for the project, in this case 'app'
app.use(express.favicon());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
});
http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
Start node js server using
$ node server.js
It will start express server, and you can access it by typing in browser window
localhost:3000
It will be good to look at Yeoman and install Angular Generator. This is just to setup proper angular js project without error. If you have your own structure thats fine.