29
loading...
This website collects cookies to deliver better user experience
Node.js is an open-source, cross-platform, back-end, JavaScript runtime environment that executes JavaScript code outside a web browser.
// File: app.js
const http = require('http');
const port = 8081;
http.createServer((request, response) => {
// Set response status code and response headers
response.writeHead(200, { 'Content-Type': 'text/html' });
// Set response body i.e, data to be sent
response.write('<h1>TODO</h1>');
// Tell the server the response is complete and to close the connection
response.end();
}).listen(port, () => {
// Log text to the terminal once the server starts
console.log(`Nodejs server started on port ${port}`)
});
node app.js
in the terminal. You will see the following in terminal-Nodejs server started on port 8081
curl
:curl -X GET http://localhost:8081
http://localhost:8081
in your browser to see the response sent by the above server.http
is an inbuilt Node module, you can use require()
to import it.createServer()
which can be used to create an HTTP server.request
and response
objects.response
object methods -response.write()
calls before response.end()
is called to send more data.<h1>TODO<h1>
Nodejs server started on port 8081
to make sure that server is listening.const { method, url } = request;
//fetch request method and path by using the request object’s method and url properties.
if (url == "/todos") {
if (method == "GET") {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write('<h1>TODO</h1>');
response.write('<p>Track your work</p>');
} else {
response.writeHead(501); //or response.statusCode = 501
}
} else {
response.writeHead(404);
}
response.end();
curl -X GET http://localhost:8081/random
curl -X POST http://localhost:8081/todos
request
object that's passed in to a handler implements the ReadableStream
interface. This stream can be listened to or piped elsewhere just like any other stream. We can grab the data right out of the stream by listening to the stream's 'data' and 'end' events.request.on()
method can be used to look for the stream events. The data is read in chunks and is a buffer.let body = '';
request.on('error', (err) => {
console.error(err);
}).on('data', (chunk) => {
body += chunk; //keep concatenating the chunk
}).on('end', () => {
body = JSON.parse(body);
});
URL
Module-var url = require('url');
var adr = 'http://localhost:8081/default.htm?year=2017&month=february'; //request.url
var q = url.parse(adr, true);
console.log(q.host); //returns 'localhost:8081'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'
var qdata = q.query; //returns an object: { year: 2017, month: 'february' }
console.log(qdata.month); //returns 'february'
$ npm install express
HTTP
library, which can get complicated for even the most basic web servers.app.httpMethod(path, handler) {...}
GET API
to the /todos
path using Express
const app = express();
app.get("/todos", (request,response) => {
response.status(200);
response.send('<h1>TODO</h1>');
});
const port = 8081;
app.listen(port, function(){
console.log(`Nodejs server started on port ${port}`)
});
// User defined Middleware
app.use(function(req, res, next){
console.log('Inside Middleware function...');
next();
});
const express = require('express');
//importing express
const app = express();
//initializing express app
app.use(express.json())
//express.json() middleware to parse the request body as JSON.
const port = 8081
let todoList = ["Complete writing blog", "Complete project"];
/* Get all TODOS:
** curl -v http://localhost:8081/todos
*/
app.get("/todos", (request, response) => {
response.send(todoList);
});
/* Add a TODO to the list
** curl -v -X POST -d '{"name":"Plan for next week"}' http://localhost:8081/todos -H 'content-type:application/json'
*/
app.post("/todos", (request, response) => {
let newTodo = request.body.name;
todoList.push(newTodo);
response.status(201).send();
});
/* Delete a TODO to the list
** curl -v -X DELETE -d '{"name":"Complete writing blog"}' http://localhost:8081/todos
*/
app.delete("/todos", (request, response) => {
let deleteTodo = request.body.name;
console.log(deleteTodo);
for (let i = 0; i < todoList.length; i++) {
if (todoList[i] === deleteTodo) {
todoList.splice(i, 1);
response.status(204).send();
}
}
});
app.all("/todos", (request, response) => {
response.status(501).send()
})
app.all("*", (request, response) => {
response.status(404).send()
})
app.listen(port, () => {
console.log(`Nodejs server started on port ${port}`)
});
/todos
other than GET, POST and DELETE, we can use the app.all() method below the current set of routes.