Code Your First API With Node.js and Express: Set Up the Server
How to Set Up an Express API Server in Node.js
In the previous tutorial, we learned what the REST architecture is, the six guiding constraints of REST, how to understand HTTP request methods and their response codes, and the anatomy of a RESTful API endpoint.
在上一教程中,我们了解了REST体系结构是什么,REST的六个指导约束,如何理解HTTP请求方法及其响应代码以及RESTful API端点的结构
In this tutorial, we'll set up a server for our API to live on. You can build an API with any programming language and server software, but we will use Node.js, which is the back-end implementation of JavaScript, and Express, a popular, minimal framework for Node.
在本教程中,我们将为我们的API设置一个服务器。您可以使用任何编程语言和服务器软件来构建API,但是我们将使用Node.js(它是JavaScript的后端实现)和Express(一种流行的,最小的Node框架)
Installation
Our first prerequisite is making sure Node.js and npm are installed globally on the computer. We can test both using the -v
flag, which will display the version. Open up your command prompt and type the following.
我们的第一个前提条件是确保在计算机上全局安装Node.js和npm。我们可以使用-v标志进行测试,这将显示版本。打开命令提示符,然后键入以下内容
node -v && npm -v
v12.16.3
6.14.5
Your versions may be slightly different than mine, but as long as both are there, we can get started.
您的版本可能与我的版本略有不同,但是只要两者都存在,我们就可以开始
Let's create a project directory called express-api
and move to it.
让我们创建一个名为express-api的项目目录并移至该目录中
mkdir express-api && cd express-api
Now that we're in our new directory, we can initialize our project with the init command.
现在我们位于新目录中,我们可以使用init命令初始化项目
npm init
This command will prompt you to answer some questions about the project, which you can choose to fill out or not. Once the setup is complete, you'll have a package.json file that looks like this:
该命令将提示您回答有关项目的一些问题,您可以选择是否填写。设置完成后,您将获得一个如下所示的package.json文件
{
"name": "express-api",
"version": "1.0.0",
"description": "Node.js and Express REST API",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Tania Rascia",
"license": "MIT"
}
Now that we have our package.json, we can install the dependencies required for our project. Fortunately we don't require too many dependencies, just these four listed below.
现在我们有了package.json,我们可以安装项目所需的依赖项了。幸运的是,我们不需要太多的依赖关系,只需下面列出的这四个即可
- body-parser: Body parsing middleware.
- express: A minimalist web framework we'll use for our server.
- mysql: A MySQL driver.
- We'll use the
install
command followed by each dependency to finish setting up our project.
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 something like this:
{
"name": "express-api",
"version": "1.0.0",
"description": "Node.js and Express REST API",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Tania Rascia",
"license": "MIT",
"dependencies": {
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mysql": "^2.18.1"
}
}
Setting Up an HTTP Server
Before we get started on setting up an Express server, we will quickly set up an HTTP server with Node's built-in http
module, to get an idea of how a simple server works.
在开始设置Express服务器之前,我们将使用Node的内置http模块快速设置HTTP服务器,以了解简单服务器的工作方式
Create a file called hello-server.js. Load in the http
module, set a port number (I chose 3001
), and create the server with the createServer()
method.
创建一个名为hello-server.js的文件。加载http模块,设置端口号(我选择3001),然后使用createServer()方法创建服务器
// Build a server with Node's HTTP module
const http = require('http');
const port = 3001;
const server = http.createServer()
In the introductory REST article, we discussed what requests and responses are with regards to an HTTP server. We're going to set our server to handle a request and display the URL requested on the server side, and display a Hello, server! message to the client on the response side.
在介绍REST文章中,我们讨论了关于HTTP服务器的请求和响应。我们将设置服务器以处理请求,并在服务器端显示请求的URL,并显示Hello, server!消息发送给响应方的客户端
server.on('request', (request, response) => {
console.log(`URL: ${request.url}`);
response.end('Hello, server!')
})
Finally, we will tell the server which port to listen on, and display an error if there is one.
最后,我们将告诉服务器要侦听哪个端口,如果有错误,则显示错误消息
// 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 our server with node
followed by the filename.
node hello-server.js
You will see this response in the terminal:
Server is listening on port 3001
To check that the server is actually running, go to https://localhost:3001/
in your browser's address bar. If all is working properly, you should see Hello, server! on the page. In your terminal, you'll also see the URLs that were requested.
要检查服务器是否正在实际运行,需在浏览器的地址栏中访问https:// localhost:3001/ 如果一切正常,您应该看到“Hello, Server”!在页面上。在您的终端中,您还将看到所请求的URL
URL: /
URL: /favicon.ico
If you were to navigate to http://localhost:3001/hello
, you would see URL: /hello
.
如果要导航到http://localhost:3001/hello,则会看到URL: /hello
We can also use cURL on our local server, which will show us the exact headers and body that are being returned.
我们还可以在本地服务器上使用cURL,它将向我们显示返回的确切标头和正文
curl -i http://localhost:3001
HTTP/1.1 200 OK
Date: Tue, 19 May 2020 07:52:41 GMT
Connection: keep-alive
Content-Length: 13
Hello, server!
If you close the terminal window at any time, the server will go away.
Now that we have an idea of how the server, request, and response all work together, we can rewrite this in Express, which has an even simpler interface and extended features.
现在我们已经知道服务器,请求和响应如何协同工作,我们可以在Express中重写它,它具有更简单的界面和扩展功能
Setting Up an Express Server
We're going to create a new file, app.js, which will be the entry point to our actual project. Just like with the original http server, we'll require a module and set a port to start.
我们将创建一个新文件app.js,它将作为我们实际项目的入口。就像原始的http服务器一样,我们将需要一个模块并设置一个端口以启动
Create an app.js file and put the following code in it.
// Require packages and set the port
const express = require('express');
const port = 3002;
const app = express();
Now, instead of looking for all requests, we will explicitly state that we are looking for a GET
request on the root of the server (/
). When /
receives a request, we will display the URL requested and the "Hello, Server!" message.
现在,代替查找所有请求,我们将明确声明要在服务器根目录(/)上查找GET请求。当/收到请求时,我们将显示请求的URL和“Hello, Server!”信息
app.get('/', (request, response) => {
console.log(`URL: ${request.url}`);
response.send('Hello, Server!');
});// Require packages and set the port
const express = require('express');
const port = 3002;
const app = express();
Finally, we'll start the server on port 3002
with the listen()
method.
最后,我们将使用listen()方法在端口3002上启动服务器
// Start the server
const server = app.listen(port, (error) => {
if (error) return console.log(`Error: ${error}`);
console.log(`Server listening on port ${server.address().port}`);
});
We can start the server with node app.js
as we did before, but we can also modify the scripts
property in our package.json file to automatically run this specific command.
我们可以像以前一样使用node app.js启动服务器,但是我们也可以修改package.json文件中的scripts属性以自动运行此特定命令。
"scripts": {
"start": "node app.js"
},
Now we can use npm start
to start the server, and we'll see our server message in the terminal.
现在我们可以使用npm start启动服务器,并且我们将在终端中看到服务器消息
Server listening on port 3002
If we run a curl -i
on the URL, we will see that it is powered by Express now, and there are some additional headers such as Content-Type
.
如果我们在URL上运行curl -i,我们将看到它现在由Express提供支持,并且还有一些其它标头,例如Content-Type
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 42
ETag: W/"2a-jN04K6SYZAwM3XlMMD6uSsxeom4"
Date: Tue, 19 May 2020 08:03:33 GMT
Connection: keep-alive
Add Body Parsing Middleware
In order to easily deal with POST
and PUT
requests to our API, we will add body parsing middleware. This is where our body-parser
module comes in. body-parser
will extract the entire body of an incoming request and parse it into a JSON object that we can work with.
为了轻松处理对我们的API的POST和PUT请求,我们将添加主体解析中间件。这是我们的body-parser模块进入的地方。body-parser将提取传入请求的整个主体,并将其解析为我们可以使用的JSON对象
We'll simply require the module at the top of our file. Add the following require
statement to the top of your app.js file.
我们只需要在文件顶部添加模块即可。将以下require语句添加到app.js文件的顶部
const bodyParser = require('body-parser');
Then we'll tell our Express app to use body-parser
, and look for JSON.
// Use Node.js body parsing middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
Also, let's change our message to send a JSON object as a response instead of plain text.
另外,让我们更改消息以发送JSON对象作为响应而不是纯文本
response.send({message: 'Node.js and Express REST API'});
Following is our full app.js file as it stands now.
// Require packages and set the port
const express = require('express');
const port = 3002;
const bodyParser = require('body-parser');
const app = express();
// Use Node.js body parsing middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true,
}));
app.get('/', (request, response) => {
response.send({
message: 'Node.js and Express REST API'}
);
});
// Start the server
const server = app.listen(port, (error) => {
if (error) return console.log(`Error: ${error}`);
console.log(`Server listening on port ${server.address().port}`);
});
If you send a curl -i
to the server, you'll see that the header now returns Content-Type: application/json; charset=utf-8
.
Set Up Routes
So far, we only have a GET
route to the root (/
), but our API should be able to handle all four major HTTP request methods on multiple URLs. We're going to set up a router and make some fake data to display.
到目前为止,我们只有到根(/)的GET路由,但是我们的API应该能够处理多个URL上的所有四个主要HTTP请求方法。我们将设置一个路由器,并显示一些假数据
Let's create a new directory called routes, and a file within called routes.js. We'll link to it at the top of app.js.
让我们创建一个名为routes的新目录,以及一个名为routes.js的文件。我们将在app.js顶部链接到它
const routes = require('./routes/routes');
Note that the .js
extension is not necessary in the require. Now we'll move our app's GET
listener to routes.js. Enter the following code in routes.js.
请注意,require中不需要.js扩展名。现在,我们将应用程序的GET侦听器移动到route.js。在routes.js中输入以下代码。
const router = app => {
app.get('/', (request, response) => {
response.send({
message: 'Node.js and Express REST API'
});
});
}
Finally, export the router
so we can use it in our app.js file.
// Export the router
module.exports = router;
In app.js, replace the app.get()
code you had before with a call to routes()
:
在app.js中,用对routes()的调用替换之前的app.get()代码:
routes(app);
You should now be able to go to http://localhost:3002
and see the same thing as before. (Don't forget to restart the server!)
您现在应该可以访问http:// localhost:3002并看到与以前相同的内容。(不要忘记重新启动服务器!)
Once that is all set up and working properly, we'll serve some JSON data with another route. We'll just use fake data for now, since our database is not yet set up.
一旦一切都设置好并且可以正常工作,我们将通过另一条路线提供一些JSON数据。由于我们的数据库尚未建立,我们现在仅使用伪数据
Let's create a users
variable in routes.js, with some fake user data in JSON format.
让我们在route.js中创建一个users变量,其中包含一些JSON格式的虚假用户数据
const users = [{
id: 1,
name: "Richard Hendricks",
email: "richard@piedpiper.com"
},
{
id: 2,
name: "Bertram Gilfoyle",
email: "gilfoyle@piedpiper.com"
}
];
We'll add another GET
route to our router, /users
, and send the user data through.
我们将向路由器/ users添加另一个GET路由,并通过发送用户数据
app.get('/users', (request, response) => {
response.send(users);
});
After restarting the server, you can now navigate to http://localhost:3002/users
and see all our data displayed.
重新启动服务器后,您现在可以导航到http://localhost:3002/users并查看显示的所有数据
Note: If you do not have a JSON viewer extension on your browser, I highly recommend you download one, such as JSONView for Chrome. This will make the data much easier to read!
Visit our GitHub Repo to see the completed code for this post and compare it to your own.
Conclusion
In this tutorial, we learned how to set up a built-in HTTP server and an Express server in node, route requests and URLs, and consume JSON data with get requests.
在本教程中,我们学习了如何在node中设置内置HTTP服务器和Express服务器,路由请求和URL,以及通过get请求使用JSON数据
In the final installment of the RESTful API series, we will hook up our Express server to MySQL to create, view, update, and delete users in a database, finalizing our API's functionality.
在RESTful API系列的最后一部分中,我们将Express服务器连接到MySQL,以在数据库中创建,查看,更新和删除用户,从而最终确定API的功能
Code Your First API With Node.js and Express: Set Up the Server的更多相关文章
- ASP.NET Web Api vs Node.js Benchmark
http://mikaelkoskinen.net/post/asp-net-web-api-vs-node-js-benchmark ASP.NET Web Api vs Node.js Bench ...
- Node.js、express、mongodb 入门(基于easyui datagrid增删改查)
前言 从在本机(win8.1)环境安装相关环境到做完这个demo大概不到两周时间,刚开始只是在本机安装环境并没有敲个Demo,从周末开始断断续续的想写一个,按照惯性思维就写一个增删改查吧,一方面是体验 ...
- Node.js基于Express框架搭建一个简单的注册登录Web功能
这个小应用使用到了node.js bootstrap express 以及数据库的操作 :使用mongoose对象模型来操作 mongodb 如果没了解过的可以先去基本了解一下相关概念~ 首先注 ...
- Node.js系列-express(上)
前言 Node.js系列的第一篇:http,大概描述了通过使用node.js内置的api创建一个服务并监听request实现简单的增删改查.现在,我们就通过通读express官网及使用express框 ...
- node.js,express入门看详细篇
先最简单的代码 安装 npm install express app.js 代码内容 const express = require('express') const app = express() ...
- node.js使用express框架进行文件上传
关于node.js使用express框架进行文件上传,主要来自于最近对Settings-Sync插件做的研究.目前的研究算是取得的比较好的进展.Settings-Sync中通过快捷键上传文件,其实主要 ...
- node.js之express框架
之前学习过node.js接触过express框架,最近为了编写一个mock server正好用到了express.下面正好就跟大家介绍一下关于express.今天的内容主要围绕这么几个方面? expr ...
- 如何设计一个基于Node.js和Express的网站架构?
前言 今年七月份,我和几个小伙伴们合伙建立了一个开发团队.业务开展如火如荼的同时,团队宣传就提上了日程,所以迫切需要搭建公司网站出来.确定目标后我们就开始考虑如果构建一个企业网站.先是进行业内调查,看 ...
- LIGHTX-CMS —— 基于 Node.js,Express.js 以及 SQLite 3 搭建的个人博客系统
概述 LIGHTX-CMS 是我基于 Node.js,Express.js 以及 SQLite 3 搭建的个人博客发布系统. 项目本身可以拿来部署个人博客网站,同时我认为其也适合用以新手学习 Node ...
随机推荐
- C6 C7的开机启动流程
C6开机启动流程 1.内核引导,加电自检(通电后检查内核):检查bios的配置,检测硬件 装好系统之后才会进行以下内容 MBR 引导 (3.2.1...) GRUB菜单 (选择不同的系统)(按e,进入 ...
- ps 和 top
ps 进程和线程的关系: (1)一个线程只能属于一个进程,而一个进程可以有多个线程,但至少有一个线程. (2)资源分配给进程,同一进程的所有线程共享该进程的所有资源. (3)处理机分给线程,即真正在处 ...
- material UI中withStyles和makeStyles的区别
在material UI中,withStyles和makeStyles是经常使用的两个用于封装样式的函数.对于刚使用material UI的开发者而言,可能不太清楚这两者的区别. 本文简要探究 ...
- Linux指令面试题01-进程查看与终止
查看某一进程是否运行:ps -ef|grep 程序名 终止程序: kill pid 转载于:https://www.cnblogs.com/feihujiushiwo/p/10896636.html
- bzoj 4152[AMPPZ2014]The Captain
bzoj 4152[AMPPZ2014]The Captain 给定平面上的n个点,定义(x1,y1)到(x2,y2)的费用为min(|x1-x2|,|y1-y2|),求从1号点走到n号点的最小费用. ...
- flink系列-10、flink保证数据的一致性
本文摘自书籍<Flink基础教程> 一.一致性的三种级别 当在分布式系统中引入状态时,自然也引入了一致性问题.一致性实际上是“正确性级别”的另一种说法,即在成功处理故障并恢复之后得到的结果 ...
- E. Sasha and Array 矩阵快速幂 + 线段树
E. Sasha and Array 这个题目没有特别难,需要自己仔细想想,一开始我想了一个方法,不对,而且还很复杂,然后lj提示了我一下说矩阵乘,然后再仔细想想就知道怎么写了. 这个就是直接把矩阵放 ...
- B. Marvolo Gaunt's Ring 前缀后缀
B. Marvolo Gaunt's Ring 这种一般只有三个的都可以处理前缀和后缀,再枚举中间这个值. 这个和之前写过的C. Four Segments 前缀后缀 处理方式很像. #include ...
- RabbitMQ|异步
目录 RabbitMQ|异步 1 概念|异步 1.1 同步与异步 1.2 比喻 2 生产者消费者设计模式 3 RabbitMQ介绍 3.1 主流消息队列比较: 3.2 RabbitMQ安装(mac电脑 ...
- Day_08【面向对象】扩展案例2_测试旧手机新手机类,并给新手机实现玩游戏功能
分析以下需求,并用代码实现 1.定义手机类 行为: 打电话,发短信 2.定义接口IPlay 行为: 玩游戏 3.定义旧手机类继承手机类 行为: 继承父类的行为 4.定义新手机继承手机类实现IPlay接 ...