[ This is a content summary only. Visit our website http://ift.tt/1b4YgHQ for full links, other content, and more! ]
by Web Desk via Digital Information World
"Mr Branding" is a blog based on RSS for everything related to website branding and website design, it collects its posts from many sites in order to facilitate the updating to the latest technology.
To suggest any source, please contact me: Taha.baba@consultant.com
The following is a short extract from our new book, JavaScript: Novice to Ninja, 2nd Edition, written by Darren Jones. It's the ultimate beginner's guide to JavaScript. SitePoint Premium members get access with their membership, or you can buy a copy in stores worldwide.
It is a tradition when learning programming languages to start with a "Hello, world!" program. This is a simple program that outputs the phrase "Hello world!" to announce your arrival to the world of programming. We’re going to stick to this tradition and write this type of program in JavaScript. It will be a single statement that logs the phrase "Hello, world!" to the console.
To get started, you’ll need to open up your preferred console (either the Node REPL, browser console, or ES6 Console on the web). Once the console has opened, all you need to do is enter the following code:
console.log('Hello world!');
Then press Enter. if all went to plan you should see an output of "Hello, world!" displayed; similar to the screenshot below.
Congratulations, you’ve just written your first JavaScript program! It might not look like much, but a wise person once said that every ninja programmer’s journey begins with a single line of code (or something like that, anyway!).
JavaScript is an interpreted language and needs a host environment to run. Because of its origins, the main environment that JavaScript runs in is the browser, although it can be run in other environments; for example, our first program that we just wrote ran in the Node REPL. Node can also be used to run JavaScript on a server. By far the most common use of JavaScript is still to make web pages interactive. Because of this, we should have a look at what makes up a web page before we go any further.
Nearly all web pages are made up of three key ingredients ― HTML, CSS and JavaScript. HTML is used to mark up the content. CSS is the presentation layer, and JavaScript adds the interactivity.
Each layer builds on the last. A web page should be able to function with just the HTML layer ― in fact, many websites celebrate “naked day” when they remove the CSS layer from their site. A website using just the HTML layer will be in its purest form and look very old school, but should still be fully functional.
It is widely considered best practice to separate the concerns of each layer, so each layer is only responsible for one thing. Putting them altogether can lead to very complicated pages where all of the code is mixed up together in one file, causing “tag soup” or “code spaghetti”. This used to be the standard way of producing a website and there are still plenty of examples on the web that do this.
When JavaScript was initially used, it was designed to be inserted directly into the HTML code, as can be seen in this example that will display a message when a button is clicked:
<button id='button' href='#' onclick='alert("Hello World")'>Click Me</a>
This made it difficult to see what was happening, as the JavaScript code was mixed up with the HTML. It also meant the code was tightly coupled to the HTML, so any changes in the HTML required the JavaScript code to also be changed to stop it breaking.
It’s possible to keep the JavaScript code away from the rest of the HTML by placing it inside its own <script> tags. The following code will achieve the same result as that above:
<script>
const btn = document.getElementById(’link’)
btn.addEventListener('click', function() {
alert('Hello World!');
};
</script>
This is better because all the JavaScript is in one place, between the two script tags, instead of mixed with the HTML tags.
We can go one step further and keep the JavaScript code completely separate from the HTML and CSS in its own file. This can be linked to using the src attribute in the script tag to specify the file to link to:
<script src='main.js'></script>
The JavaScript code would then be placed in a file called main.js inside the same directory as the HTML document. This concept of keeping the JavaScript code completely separate is one of the core principles of unobtrusive JavaScript.
In a similar way, the CSS should also be kept in a separate file, so the only code in a web page is the actual HTML with links to the CSS and JavaScript files. This is generally considered best practice and is the approach we’ll be using in the book.
If you’ve used XML or XHTML, you might have come across self-closing tags such as this script tag:
<script src='main.js' />
These will fail to work in HTML5, so should be avoided.
You may see some legacy code that uses the language attribute:
<script src='main.js' language='javascript'></script>
This is unnecessary in HTML5, but it will still work.
Graceful degradation is the process of building a website so it works best in a modern browser that uses JavaScript, but still works to a reasonable standard in older browsers, or if JavaScript or some of its features are unavailable. An example of this are programs that are broadcast in high definition (HD) ― they work best on HD televisions but still work on a standard TV; it’s just the picture will be of a lesser quality. The programs will even work on a black-and-white television.
Progressive enhancement is the process of building a web page from the ground up with a base level of functionality, then adding extra enhancements if they are available in the browser. This should feel natural if you follow the principle of three layers, with the JavaScript layer enhancing the web page rather than being an essential element that the page cannot exist without. An example might be the phone companies who offer a basic level of phone calls, but provide extra services such as call-waiting and caller ID if your telephone supports it.
Whenever you add JavaScript to a web page, you should always think about the approach you want to take. Do you want to start with lots of amazing effects that push the boundaries, then make sure the experience degrades gracefully for those who might not have the latest and greatest browsers? Or do you want to start off building a functional website that works across most browsers, then enhance the experience using JavaScript? The two approaches are similar, but subtly different.
We’re going to finish the chapter with a second JavaScript program that will run in the browser. This example is more complicated than the previous one and includes a lot of concepts that will be covered in later chapters in more depth, so don’t worry if you don’t understand everything at this stage! The idea is to show you what JavaScript is capable of, and introduce some of the important concepts that will be covered in the upcoming chapters.
We’ll follow the practice of unobtrusive JavaScript mentioned earlier and keep our JavaScript code in a separate file. Start by creating a folder called rainbow. Inside that folder create a file called rainbow.html and another called main.js.
Let’s start with the HTML. Open up rainbow.html and enter the following code:
<head>
<meta charset='utf-8'>
<title>I Can Click A Rainbow</title>
</head>
<body>
<button id='button'>click me</button>
<script src='main.js'></script>
</body>
</html>
This file is a fairly standard HTML5 page that contains a button with an ID of button. The ID attribute is very useful for JavaScript to use as a hook to access different elements of the page. At the bottom is a script tag that links to our JavaScript file.
Now for the JavaScript. Open up main.js and enter the following code:
const btn = document.getElementById('button');
const rainbow = ['red','orange','yellow','green','blue','rebeccapurple','violet'];
function change() {
document.body.style.background = rainbow[Math.floor(7*Math.random())];
}
btn.addEventListener('click', change);
Our first task in the JavaScript code is to create a variable called btn (we cover variables in Chapter 2).
We then use the document.getElementById function to find the HTML element with the ID of btn (Finding HTML elements is covered in Chapter 6). This is then assigned to the btn variable.
We now create another variable called rainbow. An array containing a list of strings of different colors is then assigned to the rainbow variable (we cover strings and variables in Chapter 2 and arrays in Chapter 3).
Then we create a function called change (we cover functions in Chapter 4). This sets the background color of the body element to one of the colors of the rainbow (changing the style of a page will be covered in Chapter 6). This involves selecting a random number using the built-in Math object (covered in Chapter 5) and selecting the corresponding color from the rainbow array.
Last of all, we create an event handler, which checks for when the button is clicked on. When this happens it calls the change function that we just defined (event handlers are covered in Chapter 7).
Open rainbow.html in your favorite browser and try clicking on the button a few times. If everything is working correctly, the background should change to every color of the rainbow, such as in the screenshot below.
Continue reading %Hello, World! Your First JavaScript Programs%
Brutalist One Pager featuring a fun spray can cursor effect for the upcoming Integrated art & design conference.
This "Most Loved" One Page website round-up is brought to you by hosting provider, Bluehost.
Bluehost is the most affordable hosting option to host your One Page websites. They have an incredible $2.95/month deal exclusive to One Page Readers where you can host your website with 50GB diskspace and unlimited bandwidth. They also throw in a free domain!
If you want to get notified about the "Most Loved" awards each month, subscribe to our Inspiration Newsletter.
Below are the 5 One Page websites awarded “Most Loved” in September – hope you enjoy!
Impressive One Page website for the Pomorilla Pizzeria in Cupra Marittima, Italy. What a nice touch as you scroll the background morphs into different shapes similar to the dough making process. However the highlight is definitely the menu with lovely illustrations, ingredients filter and a size price switcher
Seriously impressive engaging One Pager investigating the famous 2003 student murders in Sydney. The long scrolling Singe Page website gives the unique perspective of two people with interactive content switchers. The research is thorough and the design is beautiful featuring tons of gritty textures and subtle animations as you scroll. This is the fifth Most Loved award in a row now for SBS. Respect
Engaging long-scrolling One Pager celebrating the bright looking future for the SMU Mustangs. The Singe Page site features quality video clips, a spacious arrangement of content and great typography.
‘Koya Bound’ is a beautiful interactive One Pager and photographic record of Dan Rubin and Craig Mod’s eight days walking on the Japanese pilgrimage path, Kumano Kodo. As you scroll down, the photos correlate with the map to the right, giving more context to the journey. At the bottom they promote the (limited edition) print version of the adventure. A great reference to long-form journalism in a Singe Page website – also promoting a product.
Awesome, fun-filled One Pager forming the digital résumé of a dog named Birch. There is just so much character from dog emoji-preloaders, confetti shower animations as you scroll, hilarious timelines, fun infographics and an even funnier recognition section. Lastly a shout out to the responsive adaption – especially how the confetti animation moves to the background and how the infographic changes to portrait orientation. Bravo
Hope you enjoyed these beautiful One Pagers from September!
Big love to hosting provider Bluehost for sponsoring the round up < 3
Building APIs is important; however, building secured APIs is also very important. In this tutorial, you learn how to build a secured API in Node.js. The authentication will be handled using tokens. Let's dive in.
Let's talk a little about cookies and tokens, to understand how they work and the differences between them.
Cookie-based authentication keeps an authentication record or session both on the server and the client side. In other words, it is stateful. The server keeps track of an active session in the database, while a cookie is created on the front-end to hold a session identifier.
In token-based authentication, every server request is accompanied by a token which is used by the server to verify the authenticity of the request. The server does not keep a record of which users are logged in. Token-based authentication is stateless.
In this tutorial, you will implement token-based authentication.
First, create a folder where you will be working from, and initialize npm. You can do so by running:
npm init -y
Use the package.json file I have below. It contains all the dependencies you will be making use of to build this application.
#package.json
{
"name": "api-auth",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start-dev": "nodemon app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.17.2",
"express": "^4.15.4",
"express-promise-router": "^2.0.0",
"joi": "^10.6.0",
"jsonwebtoken": "^8.0.0",
"mongoose": "^4.11.10",
"morgan": "^1.8.2",
"nodemon": "^1.12.0",
"passport": "^0.4.0",
"passport-jwt": "^3.0.0",
"passport-local": "^1.0.0"
}
}
Now you can install the dependencies by running:
npm install
You can go grab a cup of coffee as npm does its magic; you'll need it for this ride!
Create a new file called app.js. In this file, you will require some packages and do a bit of setup. Here is how it should look.
#app.js
// 1
const express = require('express')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const routes = require('./routes/users')
// 2
mongoose.Promise = global.Promise
mongoose.connect('mongodb://localhost:27017/api-auth')
const app = express()
// 3
app.use(morgan('dev'))
app.use(bodyParser.json())
// 4
app.use('/users', routes)
// 5
const port = process.env.PORT || 3000
app.listen(port)
console.log(`Server listening at ${port}`)
POST /users/signin 401 183.635 ms - -. You also require your routes (which will be created soon) and set it to routes.It's time to get our model up and running.
Your User model will do a few things:
Time to see what that should look like in real code. Create a folder called models, and in the folder create a new file called user.js. The first thing you want to do is require the dependencies you will be making use of.
The dependencies you will need here include mongoose and bcryptjs.
You will need bcryptjs for the hashing of a user password. We will come to that, but for now just require the dependencies like so.
#models/user.js
const mongoose = require('mongoose')
const bcrypt = require('bcryptjs')
With that out of the way, you want to create your user schema. This is where mongoose comes in handy. Your schema will map to a MongoDB collection, defining how each document within the collection should be shaped. Here is how the schema for your current model should be structured.
#models/user.js
...
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true,
lowercase: true
},
password: {
type: String,
required: true
}
})
In the above, you have just two fields: email and password. You are making both fields a type of String, and requiring them. The email also has an option of unique, as you will not want to different users signing up with the same email, and it is also important that the email is in lowercase.
The next part of your model will handle the hashing of the user password.
#models/user.js
...
userSchema.pre('save', async function (next) {
try {
const salt = await bcrypt.genSalt(10)
const passwordhash = await bcrypt.hash(this.password, salt)
this.password = passwordhash
next()
} catch (error) {
next(error)
}
})
The code above makes of bcryptjs to generate a salt. You also use bcryptjs to hash the user password by passing in the user's password and the salt you just generated. The newly hashed password gets stored as the password for the user. The pre hook function ensures this happens before a new record of the user is saved to the database. When the password has been successfully hashed, control is handed to the next middleware using the next() function, else an error is thrown.
Finally, you need to validate user password. This comes in handy when a user wants to sign in, unlike the above which happens for signing up.
In this part, you need to ensure a user who wants to sign in is rightly authenticated. So you create an instance method called isValidPassword(). In this method, you pass in the password the user entered and compare it with the password attributed to that user. The user is found using the email address s/he entered; you will see how this is handled soon. A new error is thrown if one is encountered.
#models/user.js
...
userSchema.methods.isValidPassword = async function (newPassword) {
try {
return await bcrypt.compare(newPassword, this.password)
} catch (error) {
throw new Error(error)
}
}
module.exports = mongoose.model('User', userSchema)
When that is all set and done, it is important you export the file as a module so it can be rightly required.
Passport provides a simple way to authenticate requests in Node.js. These requests go through what are called strategies. In this tutorial, you will implement two strategies.
Go ahead and create a file called passport.js in your working directory. Here is what mine looks like.
#passport.js
// 1
const passport = require('passport')
const JwtStrategy = require('passport-jwt').Strategy
const { ExtractJwt } = require('passport-jwt')
const LocalStrategy = require('passport-local').Strategy
const { JWT_SECRET } = require('./config/index')
const User = require('./models/user')
// 2
passport.use(new JwtStrategy({
jwtFromRequest: ExtractJwt.fromHeader('authorization'),
secretOrKey: JWT_SECRET
}, async (payload, done) => {
try {
const user = User.findById(payload.sub)
if (!user) {
return done(null, false)
}
done(null, user)
} catch(err) {
done(err, false)
}
}))
// 3
passport.use(new LocalStrategy({
usernameField: 'email'
}, async (email, password, done) => {
try {
const user = await User.findOne({ email })
if (!user) {
return done(null, false)
}
const isMatch = await user.isValidPassword(password)
if (!isMatch) {
return done(null, false)
}
done(null, user)
} catch (error) {
done(error, false)
}
}))
JwtStrategy. This object receives two important arguments: secretOrKey and jwtFromRequest. The secretOrKey will be the JWT secret key which you will create shortly. jwtFromRequest defines the token that will be sent in the request. In the above, the token will be extracted from the header of the request. Next, you do a validation to look for the right user, and an error gets thrown if the user is not found.LocalStrategy. By default, the LocalStrategy uses only the username and password parameters. Since you are making use of email, you have to set the usernameField to email. You use the email to find the user, and when the user is found, the isValidPassword() function which you created in the user model gets called. This method compares the password entered with the one stored in the database. The comparison is done using the bcryptjs compared method. Errors are thrown if any is encountered, else the user is returned.Before you jump to setting your controllers and routes, you need to create the JWT secret key mentioned above. Create a new folder called config, and a file inside called index.js. You can make the file look like this.
#config/index.js
module.exports = {
JWT_SECRET: 'apiauthentication'
}
The user controller gets called whenever a request is made to your routes. Here is how it should look.
#controllers/users.js
// 1
const JWT = require('jsonwebtoken')
const User = require('../models/user')
const { JWT_SECRET } = require('../config/index')
// 2
signToken = ((user) => {
return JWT.sign({
iss: 'ApiAuth',
sub: user.id,
iat: new Date().getTime(),
exp: new Date().setDate(new Date().getDate() + 1)
}, JWT_SECRET)
})
module.exports = {
// 3
signup: async (req, res, next) => {
console.log('UsersController.signup() called')
const { email, password } = req.value.body
const foundUser = await User.findOne({ email })
if (foundUser) {
return res.status(403).json({ error: 'Email is already in use' })
}
const newUser = new User({ email, password })
await newUser.save()
const token = signToken(newUser)
res.status(200).json({ token })
},
// 4
signin: async (req, res, next) => {
const token = signToken(req.user)
res.status(200).json({ token })
},
// 5
secret: async (req, res, next) => {
res.json({ secret: "resource" });
}
}
signToken().signToken() function gets called with the new user as an argument to create a new token.signToken() function that creates a new token.Before you create the main routes for your application, you will first create a route helper. Go ahead and create a new folder called helpers, and a file called routeHelpers.js. Here is how it should look.
#helpers/routeHelpers.js
const Joi = require('joi')
module.exports = {
validateBody: (schema) => {
return (req, res, next) => {
const result = Joi.validate(req.body, schema)
if (result.error) {
return res.status(400).json(result.error)
}
if (!req.value) { req.value = {} }
req.value['body'] = result.value
next()
}
},
schemas: {
authSchema: Joi.object().keys({
email: Joi.string().email().required(),
password: Joi.string().required()
})
}
}
Here you are validating the body of requests sent by users. This will ensure that users enter the right details when signing up or in. The details to be validated are obtained from req.body.
The routes of your application will take this format.
#routes/users.js
const express = require('express')
const router = require('express-promise-router')()
const passport = require('passport')
const passportConf = require('../passport')
const { validateBody, schemas } = require('../helpers/routeHelpers')
const UsersController = require('../controllers/users')
router.route('/signup')
.post(validateBody(schemas.authSchema), UsersController.signup)
router.route('/signin')
.post(validateBody(schemas.authSchema), passport.authenticate('local', { session: false }), UsersController.signin)
router.route('/secret')
.get(passport.authenticate('jwt', { session: false }), UsersController.secret)
module.exports = router
Save it in routes/users.js. In the above, you are authenticating each request, and then calling the respective controller action.
Now you can start up your server by running:
npm run start-dev
Open up postman and play around with your newly created API.
You can go further to integrate new features to the API. A simple Book API with CRUD actions with routes that need to be authenticated will do. In the tutorial, you learned how to build a fully fledged authenticated API.
If you’re looking for additional JavaScript resources to study or to use in your work, check out what we have available in the Envato marketplace.