Server-Side Development
Server-Side Development
URL components
host: server address
port: service port (default: 80)
path: resource path
resource: resource name
query: query string, i.e., data passed to server
hash: fragment identifier specifying a location within the resource
All components can be omitted in specific circumstances
Relative URLs may be used to referencing resources on the
same host
5 AC2070: Web Design & Programming
Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Client Request
Structure
GET /docs/index.html HTTP/1.1
(headers…)
(blank line)
Example
GET /docs/index.html HTTP/1.1
Host: www.nowhere123.com
Accept: image/gif, image/jpeg, */*
Accept-Language: en-us, fr, vi
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0;
Windows NT 5.1)
(blank line)
Example
HTTP/1.1 200 OK
Date: Sun, 18 Oct 2009 08:56:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Sat, 20 Nov 2004 07:16:26 GMT
Content-Length: 44
Content-Type: text/html
<html><body><h1>It works!</h1></body></html>
Request Access
BROWSER Response Reception Control
Operating System
Client Machine Transaction Resource
Log Handler
Server Machine
4 layers:
Client: consists of web browsers
Server: handles client requests
Application: handles the business logic
Data: consists of storage systems
15 AC2070: Web Design & Programming
Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Express
Most popular Node.js framework to create websites
Core features
Rule-based routing table
Non-blocking event-based
I/O (Node.js feature)
→ able to handle massive
number of requests
Dynamic HTML page
rendering using templates
Middleware
Installation
npm install express
app.listen(port, () => {
console.log(`Working at http://localhost:${port}`);
});
//...
//...
Example:
app.get('/example', (req, res, next) => {
console.log('Callback #1');
next();
}, (req, res, next) => {
console.log('Callback #2');
next();
}, (req, res) => {
res.send('Hello from callback #3');
});
Method Description
res.download() Prompts a file to be downloaded
res.end() Ends the response process
res.json() Sends a JSON response
res.jsonp() Sends a JSON response with JSONP support
res.redirect() Redirects a request
res.render() Renders a review template
res.send() Sends a response of various types
res.sendFile() Sends a file as a byte stream
res.sendStatus() Sets the response status code and sends its representation as the
response body
Match /download/data.zip
app.get('/download/:name.:ext', (req, res) => {
console.log(req.params.name);
console.log(req.params.ext);
// ...
});
Examples:
Match ab, ab1, ab123, ab222,...
app.get(/^\/ab[0-9]*$/, ...
app.use('/public', express.static('public-files', {
dotfiles: 'ignore', // ignores . and .. files
extensions: ['htm', 'html'], // serves only html
index: false, // no index files
maxAge: '1d', // cache expiring date
// additional headers
setHeaders: (res, path, stat) => {
res.set('x-timestamp', Date.now());
}
}));
<main>
<div class="jumbotron">
<h1>This is great</h1>
<p>Welcome to templating using EJS</p>
</div>
</main>
[page content]
Browser sends back all previously stored cookies to the server
GET /sample_page.html HTTP/1.1
Host: www.example.org
Cookie: theme=dark; font_size=big
SameSite=Strict
Cookie sent when the site for the cookie matches the site currently
shown in the browser’s URL bar, and the user has not landed on the
site by following the link from another site
SameSite=Lax
Cookie sent when the site for the cookie matches the site currently
shown in the browser’s URL bar
SameSite=None
Cookie always sent
Secure must be set explicitly on modern browsers
SameSite not specified
Defaulted to Lax on modern browsers
52 AC2070: Web Design & Programming
Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Exercise
Create a page that allow the user to choose theme
options (colors, font size), and use cookies to make the
user preferences persistent
app.use(session({
store: new FileStore({path: './sessions'}),
secret: 'secret-password',
cookie: { maxAge: 15*60000 },
saveUninitialized: true,
resave: false
}));
Session data: use req.session object
try {
const conn = await mysql.createConnection({
host : 'server-address',
user : 'me',
password : 'secret',
database : 'my_db'
});
console.log('Connected to MySQL');
} catch(err) {
console.error(err);
}
Close connection
conn.end();
rows.forEach(e => {
console.log(e.author);
console.log(e["title"]);
});
} catch(err) {
//...
}
console.log(rows.insertId);
❑ AJAX
❑ Fetch API
❑ CORS
serialize (encode)
Data JSON
(arbitrary type) (string)
deserialize (decode)
const ul = document.getElementById("li.list");
ret.list.forEach(e => {
const el = document.createElement("li");
el.setAttribute("value", e.id);
el.innerHTML = `${e.title} (${e.author})`;
ul.appendChild(el);
});
};
res.json({
msg: "OK",
list: data.map(e => ({
authorId: e.id,
authorName: e.author,
bookTitle: e.title
})
});
} catch (err) {
res.json({ msg: err });
}
});
// CORS middleware
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', ['*']);
res.append('Access-Control-Allow-Methods',
'DELETE,GET,PATCH,POST,PUT');
res.append('Access-Control-Allow-Headers',
'Content-Type,Authorization');
if (res.method == 'OPTIONS')
res.send(200); // Only headers for preflight requests
else next(); // Continue the process for other ones
});
Installation
npm install cors
Usage
const express = require('express');
const cors = require('cors');
const app = express();
User input
a'; UPDATE users SET password='xyz' WHERE name='a
Countermeasures
Filter and validate all user input
Escape all parameters in SQL queries
Use prepared statements
Countermeasures:
Always use POST methods for requests that make changes on server
Use SameSite cookie attribute
Use one-time tokens
Apply CORS (Cross-origin resource sharing) measures
83 AC2070: Web Design & Programming
Đào Trung Kiên @ MICA Institute & Dept. of Comm. Eng., SEEE, Hanoi Univ. of Science and Technology
Other Considerations
Avoid storing sensitive information on client (cookie, local
storage)
Avoid session hijacking
Protect passwords with hashing and salts
Encrypt transmitted data
Use HTTPS
Source:
roadmap.sh