Node.js http.ClientRequest.protocol 方法
http.ClientRequest.protocol是HTTP模块中ClientRequest类的内置应用程序接口,用于获取客户端请求协议的对象。
句法:
const request.protocol
参数:此函数不接受任何参数作为参数。
返回值:该方法返回客户端请求协议的对象。
示例 1:文件名-index.js
Javascript
// Node.js program to demonstrate the
// request.protocol method
// Importing http module
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('okay');
});
// Now that server is running
server.listen(3000, '127.0.0.1', () => {
// Make a request
const options = {
port: 3000,
host: '127.0.0.1',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket'
}
};
// Getting client request
const req = http.request(options);
req.protocol = 'HTTP'
// Getting protocol
// by using protocol method
const v = req.protocol;
// Display the result
console.log("protocol :- " + v)
process.exit(0)
});
Javascript
// Node.js program to demonstrate the
// request.protocol method
// Importing http module
const http = require('http');
// Create an HTTP server
http.createServer((req, res) => { })
.listen(3000, '127.0.0.1', () => {
// Getting client request
const req = http.request({
port: 3000,
host: '127.0.0.1',
});
// Getting protocol
// by using protocol method
console.log("protocol :- " + req.protocol)
process.exit(0)
});
使用以下命令运行index.js文件:
node index.js
输出:
protocol :- HTTP
示例 2:文件名-index.js
Javascript
// Node.js program to demonstrate the
// request.protocol method
// Importing http module
const http = require('http');
// Create an HTTP server
http.createServer((req, res) => { })
.listen(3000, '127.0.0.1', () => {
// Getting client request
const req = http.request({
port: 3000,
host: '127.0.0.1',
});
// Getting protocol
// by using protocol method
console.log("protocol :- " + req.protocol)
process.exit(0)
});
使用以下命令运行index.js文件:
node index.js
输出:
protocol :- undefined
参考:https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_protocol