{"id":2857,"date":"2021-03-03T01:08:00","date_gmt":"2021-03-03T01:08:00","guid":{"rendered":"https:\/\/www.htmlgoodies.com\/uncategorized\/working-with-restful-web-services-in-javascript-creating-your-first-web-service\/"},"modified":"2021-03-03T01:08:00","modified_gmt":"2021-03-03T01:08:00","slug":"working-with-restful-web-services-in-javascript-creating-your-first-web-service","status":"publish","type":"post","link":"https:\/\/www.htmlgoodies.com\/javascript\/working-with-restful-web-services-in-javascript-creating-your-first-web-service\/","title":{"rendered":"Working with RESTful Web Services in JavaScript – Creating Your First Web Service"},"content":{"rendered":"
Some developers consider themselves to be server-side specialists, while others focus most of their efforts on client-side coding. The departments of IT shops often reflect those tendencies. However, that need not be the case. Thanks to the emergence of technologies like Node.js, you can write both the server and client components using essentially the same language. In this series on RESTful Web services we’ll cover how to to do it all using JavaScript. Today’s installment will focus on setting up a basic Web service using Node.js and the Express framework.<\/p>\n
The original JavaScript language that we all know and love can only run within the confines of a web browser. The creators of Node.js took Chrome’s V8 JavaScript engine and tailored it for building scalable network applications that run on the server-side. And if that wasn’t good enough, several frameworks have cropped up to make server-side development even easier! One such framework is Express. It’s an application framework that provides a robust set of features specifically for web and mobile applications.<\/p>\n
Here’s a Node.js service that listens for requests on port 3000 and returns a “Hello World” message:<\/p>\n
const http = require('http');\nconst hostname = '127.0.0.1';\nconst port = 3000;\n\nconst server = http.createServer((req, res) => {\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text\/plain');\n res.end('Hello World');\n});\n\nserver.listen(port, hostname, () => {\n console.log(`Server running on port ${port}\/`);\n});\n<\/pre>\nLet’s compare that to the same service built with Express:<\/p>\n
const express = require('express');\nconst server = express();\nconst port = 3000;\n\nserver.get('\/', (req, res) => {\n res.send('Hello World!')\n})\n\nserver.listen(port, () => {\n console.log(`Server running on port ${port}`);\n});\n<\/pre>\nWhile you certainly do not need Express to write Web services, it does offer several benefits, including more succinct code, HTTP utility methods and middleware, improved performance, to name a few.<\/p>\n
What are Web Services?<\/h2>\n
Not everyone agrees on what distinguishes a web service from regular HTTP requests, APIs, Service Oriented Architecture, etc., but, for the purposes of this series, let’s define a web service as any piece of software that makes itself available over the Internet using a standardized data transfer protocol such as XML or JSON to encode all communications between it and clients. You could even use plaintext for very simple services, but, in most cases, employing a standardized data transfer protocol will allow your service to communicate with clients on any operating system as well as built using any programming language. Hence, a Java service can communicate with an Angular client and a Windows server can respond to requests from Unix applications. There are some other criteria such as being discoverable via a simple find mechanism, but that is beyond the scope of this series.<\/p>\n
A RESTful Web Service is one that is built on the REST architecture. REST stands for “REpresentational State Transfer”. It’s been around ever since 2004, when the web consortium released the definition of the RESTful standard. Since that time, the REST standard has become quite popular and is now being used by many of the most popular websites around the world including Facebook and Twitter.<\/p>\n
There are other types of Web services as well, the other main one being SOAP. Short for “Simple Object Access Protocol, it’s a very old web services access protocol that was originally developed by Microsoft. It’s considered to be a bit of a dinosaur nowadays and is rarely encountered any more. Having had the opportunity to work with SOAP a few years back, I can see why REST eclipsed it.<\/p>\n
Getting Started<\/h2>\n
There are few piece that you’ll need in place in order to follow along with this series:<\/p>\n
Our server app will be comprised of two files: a JavaScript file and a package.json file. The package.json file contains information about the application, including the name of the app, version, a description, and the entry point of the application.<\/p>\n
There are a few ways to generate it. We could use the Express generator, but it creates the scaffolding for a full app with numerous JavaScript files, Jade templates, and extra sub-directories. Instead, we’ll create it using the Node Package Manager (npm) that comes with Node.js:<\/p>\n
Here’s what mine looks like:<\/p>\n
{\n \"name\": \"rest-server\",\n \"version\": \"1.0.0\",\n \"description\": \"A basic REST server.\",\n \"main\": \"server.js\",\n \"scripts\": {\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n },\n \"author\": \"Rob Gravelle\",\n \"license\": \"ISC\"\n}\n<\/pre>\nInstalling Express<\/h2>\n
We can also use npm to install dependencies like Express. Here’s the command to do that:<\/p>\n
npm install express --save\n<\/pre>\nThe -save flag tells npm to add express as a dependency in our package.json file.<\/p>\n
The Server Code<\/h2>\n
All we need now is a server.<\/p>\n
\n
- Create a new file using the New File button in the VS Code EXPLORER and name it “server.js”. If you don’t see the New File button, it’s because it only comes up when you hover over the EXPLORER pane:\n
<\/p>\n<\/li>\n
- Add the following code to the new server.js file:\n
const express = require(\"express\");\nconst app = express();\n\napp.listen(3000, () => {\n console.log(\"Server running on port 3000\");\n});\n<\/pre>\n<\/li>\n<\/ol>\nAnd that’s all there is to it. We’ve got ourselves a new server!<\/p>\n
Running the App<\/h2>\n
To run your app, issue the node app.js<\/em> command in the VS Code terminal. You should see our console.log() message displayed:<\/p>\n
<\/p>\n
Conclusion<\/h2>\n
In part one of this series on RESTful Web services we set up a basic Web service using Node.js and the Express framework. You can see the fruits of our labors in the demo below:<\/p>\n