Node.js 中的 send()、sendStatus() 和 json() 方法
send() 和 json() 函数用于直接从服务器向客户端发送响应。send() 方法将数据以字符串格式发送,而 json() 函数将数据以 JSON 格式发送。sendStatus() 方法用于向客户端发送 HTTP 请求状态。可能的狀態值包括:200(成功)、404(未找到)、201(已创建)、503(服务器不可达)等。
前提条件
Node.js
Express.js
安装
使用以下语句安装 express 模块:
npm install express
示例 - sendStatus()
创建一个名为 sendStatus.js 的文件,并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示:
node sendStatus.js
sendStatus.js
// Importing the express module
const express = require('express');
const app = express();
// Sending the response for '/' path
app.get('/' , (req,res)=>{
// Status: 200 (OK)
res.sendStatus(200);
})
// Setting up the server at port 3000
app.listen(3000 , ()=>{
console.log("server running");
});输出
C:\home
ode>> node sendStatus.js
现在,从您的浏览器访问以下 URL 来访问网页:https://:3000

示例 - send()
创建一个名为 send.js 的文件,并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示:
node send.js
send.js
// Importing the express module
const express = require('express');
const app = express();
// Initializing the heading with the following string
var heading = "Welcome to TutorialsPoint !";
// Sending the response for '/' path
app.get('/' , (req,res)=>{
// Sending the heading text
res.send(heading);
})
// Setting up the server at port 3000
app.listen(3000 , ()=>{
console.log("server running");
});输出
C:\home
ode>> node send.js
现在,从您的浏览器访问以下 URL 来访问网页:https://:3000

示例 - json()
创建一个名为 json.js 的文件,并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示:
node json.js
json.js
// Importing the express module
const express = require('express');
const app = express();
// Initializing the data with the following json
var data = {
portal: "TutorialsPoint",
tagLine: "SIMPLY LEARNING",
location: "Hyderabad"
}
// Sending the response for '/' path
app.get('/' , (req,res)=>{
// Sending the data json text
res.json(data);
})
// Setting up the server at port 3000
app.listen(3000 , ()=>{
console.log("server running");
});输出
C:\home
ode>> node json.js
现在,从您的浏览器访问以下 URL 来访问网页:https://:3000

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP