0% found this document useful (0 votes)
33 views27 pages

PHP Introduction Chapter 1

The document discusses web servers and how they handle HTTP requests from clients like web browsers. It explains that web servers typically deliver HTML, images, stylesheets and scripts. It then describes the typical layers of a web application architecture, including the client, server, business and data layers. It also provides details on how to create an HTTP server using Node.js, including using the built-in HTTP module, creating a server, handling requests and responses, and reading/writing files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views27 pages

PHP Introduction Chapter 1

The document discusses web servers and how they handle HTTP requests from clients like web browsers. It explains that web servers typically deliver HTML, images, stylesheets and scripts. It then describes the typical layers of a web application architecture, including the client, server, business and data layers. It also provides details on how to create an HTTP server using Node.js, including using the built-in HTTP module, creating a server, handling requests and responses, and reading/writing files.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

JUST UNIVERSITY

Ch03
Web Modules

Eng. Abdirahman A. Mohamed (Eng.Baabale)

1
Web Server
• A Web Server is a software application which handles HTTP
requests sent by the HTTP client, like web browsers, and
returns web pages in response to the clients. Web servers
usually deliver html documents along with images, style
sheets, and scripts.

• Most of the web servers support server-side scripts, using


scripting languages or redirecting the task to an application
server which retrieves data from a database and performs
complex logic and then sends a result to the HTTP client
through the Web server.
Web Application Architecture
• A Web application is usually divided into four layers
Example
Continue…
• Client − This layer consists of web browsers, mobile
browsers or applications which can make HTTP
requests to the web server.
• Server − This layer has the Web server which can
intercept the requests made by the clients and pass
them the response.
• Business − This layer contains the application server
which is utilized by the web server to do the required
processing. This layer interacts with the data layer via
the database or some external programs.
• Data − This layer contains the databases or any other
source of data.
HTTP MODULE
• Node.js has a built-in module called HTTP, which
allows Node.js to transfer data over the Hyper Text
Transfer Protocol (HTTP).
• To include the HTTP module, use the require() method:

var http = require('http');

The HTTP module can create an HTTP server that listens


to server ports and gives a response back to the client
Creating Server
• const http = require('http');
const server =
http.createServer((req , res)=>{
• console.log('codsiga serverka wa la aqbaly');
• });
server.listen(2000 , 'localhost',
()=>{
• console.log('wan darnay server-ka');
• });
Continue..
• var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-
Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(8080);
Continue…
• const http = require("http");

• const host = 'localhost';


• const port = 8000;

• const requestListener = function (req, res) {};

• const server = http.createServer(requestListener);


• server.listen(port, host, () => {
• console.log(`Server is running on http://${host}:${port}`);
• });
server
• const http = require('http')

const host = 'localhost';
• const port = 8000;

const requirelistener = function(req , res){};

const server = http.createServer(requirelistener);
• server.listen(port , host,()=>{
• console.log(`server is running
http://localhost${host}:${port}`);
• })
CreateServer()
• createServer() : method to create an HTTP server:

• The function http.createServer() method, will be


executed when someone tries to access the computer
on port 8080.

• The http. createServer() method turns your computer


into an HTTP server. The http. createServer() method
creates an HTTP Server object
res.writeHead() and res.end()
• The res. writeHead( ) method is for returning a status code to the

browser, and the browser will throw an error if it is a client-side

status code or server-side status code.

• The res.end( ) method ends the current response process. This

method is used to quickly end the response without any data. If

one needs to respond with data, they should use either

the res.send( ) method or the res.json() method


Statuscode
• An HTTP status code is a message a website's server sends to the browser

to indicate whether or not that request can be fulfilled.

• The HTTP 200 OK success status response code indicates that the request

has succeeded

• Not found 404 The server has not found anything matching the URI given

• 301: A server returns a 301 HTTP response when the requested URL has

moved permanently to a new URL. If a user tries to visit the old URL, it

will return a 301 HTTP status, pointing the browser to the new URL. If you

move a page without adding a 301 redirect, users trying to visit the old

URL will see a 404 error. Plus, using a 301 HTTP status will pass full link

juice to the final URL.


Continue..
• The req.method property contains a string
corresponding to the HTTP method of the request
which can be either GET, POST, PUT, DELETE, etc.

• The server.listen() method creates a listener on the


specified port or path.

• Content-Type header provides the client with the actual


content type of the returned content
HTTP request methods

• HTTP defines a set of request methods to indicate the desired action to be


performed for a given resource
• GET

• The GET method requests a representation of the specified resource. Requests


using GET should only retrieve data.
• HEAD

• The HEAD method asks for a response identical to a GET request, but without
the response body.
• POST

• The HTTP POST method sends data to the server. The type of the body of the
request is indicated by the Content-Type header.
Request Object Properties
Following is the list of few properties associated with request object.
Display Text from Browser:
• const http = require('http');

const server = http.createServer((req , res)=>{
• console.log(req.url , req.method);

res.setHeader('Content-type' , 'Text/plain');
• res.write('welcome my website');
• res.end();
• });

server.listen(2000 , 'localhost', ()=>{


• console.log('wan darnay server-ka');
• });
Reading file Html to the Browser:
• const http = require('http');
• const fs = require('fs');

const server = http.createServer((req , res)=>{
• console.log(req.url , req.method);
res.setHeader('Content-type' , 'Text/html');
fs.readFile('./viw/new.html',(err , data)=>{
if(err){
• console.log(err);
• res.end();
}
• else{
• res.end(data);
• }
• });
• });
• server.listen(2000 , 'localhost', ()=>{
• console.log('wan darnay server-ka');
• });
Creating html pages :

•const http = require('http');


•const fs = require('fs');

•const server = http.createServer((req , res)=>{
•console.log(req.url , req.method);

•res.setHeader('Content-type' , 'Text/html');
•let path = './viw/';
•switch(req.url){
• case '/':
• path += 'index.html';
• break;
• case '/new':
• path += 'new.html';
• break;
• case '/about':
• path += 'about.html';
• break;
• default:
• path += 'err.html';
• break;
•}
•fs.readFile(path ,(err , data)=>{

• if(err){
• console.log(err);
• res.end();

• }
• else{
• res.end(data);
• }
•});
Upload Files
Create a Node.js file that writes an HTML form, with an upload field:
• var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200,
{'Content-Type': 'text/html'});
res.write('<form action="fileupload"
method="post" enctype="multipart/form-data">');
res.write('<input type="file"
name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}).listen(8080);
Formidable module
• Include the Formidable module to be able to parse
the uploaded file once it reaches the server.

• When the file is uploaded and parsed, it gets placed


on a temporary folder on your computer.
Formidable module
• var http = require('http');
var formidable = require('formidable');

http.createServer(function (req, res) {


if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
res.write('File uploaded');
res.end();
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post"
enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
Formidable module
• var http = require('http');
var formidable = require('formidable');
var fs = require('fs');

http.createServer(function (req, res) {


if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.filepath;
var newpath = 'C:/Users/Your Name/' +
files.filetoupload.originalFilename;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post"
enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(8080);
File uploaded with another palace
• const http = require('http')
• const formidable = require('formidable');
• const fs = require('fs')
• http.createServer(function(req , res){
• if(req.url == '/fileupload'){
• var form = new formidable.IncomingForm();
• form.parse(req , (err , fields , files)=>{
• var oldpath = files.filetoupload.filepath;
• var newpath
='C:/Users/hp/Desktop/'+files.filetoupload.originalFilename;
• fs.rename(oldpath , newpath ,function(err){
• if(err) throw err;
• res.write('file upload removed');
• });
• });
• } else { res.writeHead(200, {'Content-Type': 'text/html'});
• res.write('<form action="fileupload" method="post"
enctype="multipart/form-data">');
• res.write('<input type="file" name="filetoupload"><br>');
• res.write('<input type="submit">');
• res.write('</form>');
• return res.end();
• }}).listen(8080);
Date and Time Module
• exports.myDateTime = function () {
• return Date();
• };

• var http = require('http');


• var dt = require('./module');

http.createServer(function (req, res) {
• res.writeHead(200, {'Content-Type': 'text/html'});
• res.write("The date and time are currently: " + dt.myDateTime());
• res.end();
• }).listen(8080);
END
27

You might also like