http.ClientRequest.setHeader()是HTTP模塊內的ClientRequest類的內置應用程序編程接口,該接口用於設置標頭的對象。
用法:
const request.setHeader(name, value)
參數:此方法將特定標頭的名稱和值作為參數作為鍵值對。
返回值:此方法無返回值。
範例1:Filename-index.js
Javascript
// Node.js program to demonstrate the
// request.setHeader() 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',
});
req.setHeader('content-type', 'text/html');
console.log("before operation:- "
+ req.getHeader('content-type'))
// Removing header by using
// removeHeader() method
req.removeHeader('content-type')
console.log("after operation:- "
+ req.getHeader('content-type'))
process.exit(0)
});
使用以下命令運行index.js文件:
node index.js
輸出:
before operation:- text/html after operation:- undefined
示例2:Filename-index.js
Javascript
// Node.js program to demonstrate the
// request.setHeader() 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.setHeader('Cookie', ['type=ninja',
'language=javascript']);
console.log("before operation:- "
+ req.getHeader('Cookie'))
// Removing header by using
// removeHeader() method
req.removeHeader('Cookie')
console.log("after operation:- "
+ req.getHeader('Cookie'))
process.exit(0)
});
使用以下命令運行index.js文件:
node index.js
輸出:
before operation:- type=ninja,language=javascript after operation:- undefined
參考:https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_request_setheader_name_value
相關用法
- Node.js console.timeLog()用法及代碼示例
- Node.js fs.fsyncSync()用法及代碼示例
- Node.js process.nextTick()用法及代碼示例
- Node.js GM charcoal()用法及代碼示例
- Node.js GM blur()用法及代碼示例
- Node.js GM sharpen()用法及代碼示例
- Node.js GM drawLine()用法及代碼示例
- Node.js GM drawArc()用法及代碼示例
- Node.js GM drawPolyline()用法及代碼示例
- Node.js GM drawBezier()用法及代碼示例
- Node.js GM drawCircle()用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Node.js http.ClientRequest.setHeader() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。