JavaScript Backend Example
Here’s a simple example of a JavaScript backend application using Node.js and Express.js to create a basic API. This code sets up a basic Express.js server with a single endpoint (/users
) that responds with a JSON array of user data when accessed via a GET request.
Javascript
const express = require( 'express' ); const app = express(); let users = [ { id: 1, name: 'John Doe' , email: 'john@example.com' }, { id: 2, name: 'Jane Smith' , email: 'jane@example.com' } ]; // Get all users app.get( '/users' , (req, res) => { res.json(users); }); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server is running on port ${port}`); }); |
Explanation
- Import Express: We import the Express.js framework to create our server and define routes.
- Create Express App: We create an instance of the Express application by calling
express()
, which returns an Express application object stored in theapp
variable. - Define Dummy User Data: We define a dummy array called
users
containing some sample user data. This data will be returned when the/users
endpoint is accessed. - Define Route to Get All Users: We use the
app.get()
method to define a route for handling GET requests to the/users
endpoint. When a GET request is made to this endpoint, the callback function(req, res)
is executed. In this function, we simply send theusers
array as a JSON response usingres.json(users)
. - Start the Server: We specify a port for the server to listen on (defaulting to 3000 if no
PORT
environment variable is set) and call theapp.listen()
method to start the server. We also log a message to the console indicating that the server is running and on which port.
JavaScript for Backend Development
JavaScript is primarily known as a client-side scripting language, but with the advent of Node.js, it has also become popular for backend development.
Here are some basics of JavaScript backend development:
Table of Content
- What is backend development?
- Why JavaScript for backend development?
- Getting started with JavaScript for the backend
- JavaScript Backend Example
- Popular JavaScript backend frameworks
- Pros and Cons of Using JavaScript as a Back-End Language