In the previous tutorial, we learned about the REST architecture, the six constraints of REST, how to understand the HTTP request method and its response code, and the composition of the RESTful API endpoint.
This tutorial will set up a server for our API. You can build APIs using any programming language and server software, but we will use Node.js (the backend implementation of JavaScript) and Express (a popular, minimalist Node framework).
Our first premise is to ensure that Node.js and npm are installed globally on the computer. We can test both with express-api
and switch to it.
mkdir express-api && cd express-api
Now that we are in the new directory, we can initialize our project with the installation commands along with each dependency to complete the project's setup.
npm install body-parser express mysql request
This will create a package-lock.json
file and a node_modules
directory, and our package.json
will be updated to look like this:
{ "name": "express-app", "version": "1.0.0", "description": "", "main": "index.js", "author": "AsyncBanana", "license": "MIT", "dependencies": { "body-parser": "^1.19.2", "express": "^4.17.3", "mysql": "^2.18.1", "node-fetch": "^3.2.0" } }
Then we need to add the "scripts" object. The "scripts" object can help us run the code.
{ "name": "express-app", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "node index.js" }, "author": "AsyncBanana", "license": "MIT", "dependencies": { "body-parser": "^1.19.2", "express": "^4.17.3", "mysql": "^2.18.1", "node-fetch": "^3.2.0" }, "type": "module" }
The ECMAScript module (or ESM) is a new specification for connecting scripts in environments such as browsers and Nodes. It replaces old specifications such as CommonJS (CJS) used by Node by default. In this tutorial, we will use all ESMs.
Before starting to set up the Express server, we will use Node's built-in http
module to quickly set up an HTTP server and set a port number (I chose createServer()
method).
// Build the server using Node's HTTP module import { createServer } from "http"; const port = 3001; const server = createServer();
In the introductory REST article, we discuss requests and responses about HTTP servers. We will set up our server to process the request, display the requested URL on the server side, and display the "Hello, server!" message to the client on the response side.
server.on("request", (request, response) => { console.log(`URL: ${request.url}`); response.end("Hello, server!"); });
Finally, we will tell the server which port to listen to and display an error when it appears.
// Start the server server.listen(port, (error) => { if (error) return console.log(`Error: ${error}`); console.log(`Server is listening on port ${port}`); });
Now we can start the server by running the npm script we created earlier.
npm start
You will see this response in the terminal:
<code>Server is listening on port 3001</code>
To check if the server is running, visit https://localhost:3001/hello
and you will see the GET request on the server root directory ( /
Receive the request, we will display the requested URL and the "Hello, Server!" message).
app.get("/", (request, response) => { console.log(`URL: ${request.url}`); response.send("Hello, Server!"); });
Finally, we start the server on the port on listen()
method.
const server = app.listen(port, (error) => { if (error) return console.log(`Error: ${error}`); console.log(`Server listening on port ${server.address().port}`); });
Now we can use curl -i
for the URL, we will see that it is now powered by Express and there are some extra headers like POST
and body-parser
modules. Add the import
statement to the top of the index.js
file.
import bodyParser from "body-parser"; ...
Then we will tell our Express application to use curl -i
to the server and you will see that the header now returns GET
to route to the root directory ( .js
extension is not required in require
. Now we will move the application's router so that we can use it in the index.js
file.
// Export router export default router;
In index.js
, replace the route:
routes(app);
You should now be able to go to the users
variable in routes.js
that contains some fake user data in JSON format.
const users = [ { id: 1, name: "Richard Hendricks", email: "richard@piedpiper.com", }, { id: 2, name: "Bertram Gilfoyle", email: "gilfoyle@piedpiper.com", }, ];
We will add another /users
and send user data through it.
app.get("/users", (request, response) => { response.send(users); });
After restarting the server, you can now navigate to http://localhost:3002/users
and view all the data we display.
Note: If you don't have a JSON viewer extension on your browser, I highly recommend you download one, such as Chrome's JSONVue. This will make the data easier to read!
Visit our GitHub repository to view the full code of this article and compare it to your own.
In this tutorial, we learned how to set up a built-in HTTP server and Express server in Node, route requests and URLs, and use get requests to use JSON data.
In the final issue of the RESTful API series, we will connect our Express server to MySQL to create, view, update, and delete users in the database to complete the functionality of the API.
The above is the detailed content of Code Your First API With Node.js and Express: Set Up the Server. For more information, please follow other related articles on the PHP Chinese website!