从 Node.js 服务器向浏览器发送响应
App.js −
const http = require('http');
const server = http.createServer((req, res)=>{
console.log(req.url, req.method, req. headers);
});
server.listen(3000);如上例所示,我们在 createServer 方法中将请求和响应参数对象作为参数。
Response (res) 对象将用于向客户端发送数据。它有很多属性,下面解释一些:
res.setHeader(‘Content-Type’, ‘text/html’); 这行代码将响应内容的格式设置为 text/html。
如何从 Node.js 发送 html 内容
响应对象上的 write() 函数方法可用于发送多行 html 代码,如下所示。
res.write(‘<html>’); res.write(‘<head> <title> Hello TutorialsPoint </title> </head>’); res.write(‘ <body> Hello Tutorials Point </body>’); res.write(‘</html>’); //write end to mark it as stop for node js response. res.end(); //end () is function to mark a stop for node js write function.
一旦写入 end(),之后就不能再对同一个响应对象进行写入,否则会导致代码执行错误。
现在,我们将运行响应代码。
包含响应的完整 App.js:
const http = require('http');
const server = http.createServer((req, res)=>{
console.log(req.url, req.method, req. headers);
res.write('<html>');
res.write('<head> <title> Hello TutorialsPoint </title> </head>');
res.write(' <body> Hello Tutorials Point </body>');
res.write('</html>');
//write end to mark it as stop for node js response.
res.end();
});
server.listen(3000);在终端运行:node App.js
打开浏览器并导航到 localhost:3000,我们将在浏览器上看到以下输出。

在接下来的文章中,我们将使用 express.js 简化从 Node 发送响应的过程。
标头在 HTTP 请求和响应中都很重要。它们有助于识别服务器和客户端的正确内容类型和接受类型。Cache-control 就是这样一个标头,它决定服务器和客户端之间的缓存机制。
在单页应用程序中,令牌用于身份验证请求。会话管理也使用 HTTP 会话进行处理。
请求和响应安全机制也根据所选择的用于在客户端和服务器之间传输数据的 HTTP 方法而有所不同。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP