**OUR ASSIGNMENT**
var express = require('express');
var app = express();
app.get('/newrecipe', function(req, res) {
var User = require('../app/models/user');
res.render('newrecipe.ejs', { message: 'loggedin' });
});
app.post('/newrecipe', function(req, res) {
var newRecipe = new Recipe();
newRecipe.author_id = req.user._id;
newRecipe.name = req.body.name;
newRecipe.description = req.body.description;
res.render('newrecipe.ejs', { message: 'done'});
});
**EXAMPLE OF DEALING WITH A SIMPLE LOGIN FORM**
*HTML CODE*
<form action=”form_submitted.php” method=”GET”>
<h1>Login Form</h1>
<label> Login:</label>
<input type=”text” name=”login”><br>
<label> Password: </label>
<input type=”password” name=”password”><br>
<button type=”submit” >Log In </button>
</form>
*SERVER SIDE CODE*
var express = require(‘express’);
var router = express.Router();
router.get(‘form_submitted.php*’, function(req, res){
if (req.query.login == req.query.password){
res.send(‘Login Successful’);
} else {
res.send(‘Error: Login Failed’);
}
});
**ASSIGNMENT CODE**
var canvas = document.getElementById("game");
var context = canvas.getContext("2d");
document.getElementById("main").innerHTML = "<canvas id='"game "' width = 400 height = '"600"'> </canvas> ;
canvas = document.getElementById("game");
// Add Mouse down listener
canvas.addEventListener("mousedown", mouseDidPressDown, false);
canvas.addEventListener("mouseup", mouseDidRelease, false);
context = canvas.getContext("2d");
function mouseDidPressDown(event) {
var WIDTH = HEIGHT * 0.65;
var mousePosition = mousePositionInCanvas(event.clientX, event.clientY);
//DO WHATEVER with mousePosition.x and mousePosition.y
}
**EXAM CODE**
<body>
<canvas id='myCanvas' width='500' height='400'> Canvas not supported </canvas>
</body>
</html>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext("2d");
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left * (canvas.width / rect.width),
y: evt.clientY - rect.top * (canvas.height / rect.height)
};
}
canvas.addEventListener('click', function(evt){
var temp = getMousePos(canvas, evt);
context.translate(temp.x, temp.y);
drawCoolShape(context);
context.translate(-temp.x, -temp.y);
}, false);
</script>
**Why**
- Lightweight, free
- Modularity
- Reusable components
**What we used previously**
- Allows for DOM manipulation
- Does not provide structure to your code
<div ng-app="">
<p>Input something in the input box:</p>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>
**Some Basics**
- XML is easy to read and make automation easy, but bulky structure makes files large, can be hard to structure data into good xml format
- Javascript XML has properties and methods to structure well
**Something in XML**
<menu id="file" value="File">
<popup>
<menuitem value="New" onclick="CreateNewDoc()" />
<menuitem value="Open" onclick="OpenDoc()" />
<menuitem value="Close" onclick="CloseDoc()" />
</popup>
</menu>
**Same in JSON**
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
**Navigating JSON**
var data = JSON.Parse(file)
var fileId = data.menu.id;
var firstMenu = data.menu.popup.menuitem[0];
**What is it**: Testing for Node
**Example**:
var assert = require('assert');
var calc = require('./calc.js');
describe('Calculator Tests', function() {
it('returns 1+1=2', function(done) {
assert.equal(calc.add(1, 1), 2);
done();
});
it('returns 2*2=4', function(done) {
assert.equal(calc.mul(2, 2), 4);
done();
});
});
**Asynchronous Javascript and XML**: Not a programming language, just a way of using Javascript, Downloads data from server in background, Avoids dynamically updating a page without making the user wait
**XMLHttprequest (and why it sucks)**: Javascript includes an XMLHttprequest object that can fetch files from a web server, BUT clunky and browser incompatibilities
**JQuery**: Cross browser, simplifies javascript
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var userSchema = mongoose.Schema({
firstname : String,
lastname : String,
password : String,
phonenumber : Number,
fav_cuisine :[String],
admin : Boolean
});
// generating a hash
userSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
userSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
module.exports = mongoose.model('User', userSchema);
var requestBody = '';
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs");
PORT = 3000;
function handleRequest(request, response) {
var rest = url && url.parse(request.url).pathname;
var filePath = __dirname + request.url;
var favs = fs.readFileSync('js/favs.json');
if (chooseFile()) return;
//For each of the possible return paths, send the json file
if (request.url == "/allTweets") {
returnTweets();
} else if (request.url == "/allUsers") {
returnTweets();
}
//Function to return Json
function returnJson(json) {
response.writeHead(200);
response.end(JSON.stringify(json, null, 8));
}
//Provide the file in accordance with the
function returnFile(path, type) {
var file = fs.readFileSync(path, 'utf8');
response.writeHead(200, type);
response.end(file);
}
function chooseFile() {
if (path.extname(filePath) == '.js') {
returnFile(filePath, {"Content-Type": "text/javascript"});
return true;
}
if (rest.length <= 1) {
returnFile('./index.html', {"Content-Type": "text/html"});
return true;
}
return false;
}
}
http.createServer(handleRequest).listen(PORT);
console.log("Nodejs Server running at http://127.0.0.1:" + PORT + "/");
function change(){
$("body").find("*").hide();
var images = $("body").find("img");
images.parents().show();
images.show();
}
No comments yet.
Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.