+ 2
How to loop though object of key value pair and print them in format of name value each from new line in javascript
i am trying to have access to http request.header which will give as an object i want to loop and print them on the screen using response.write NODE JS
13 Réponses
+ 1
Abdulaziz Abdurasul Here another way using for in iteration:
const http = require('http');
const server = http.createServer((request, response)=>{
response.writeHead(200, {'Content-Type': 'text/plain'});
for (const key in request.headers) {
response.write(`${key}: ${request.headers[key]}`);
}
response.end();
}).listen(3000);
+ 2
Abdulaziz Abdurasul My apologies, I didn't read your question fully.
+ 1
Abdulaziz Abdurasul Here the code you are looking for:
const http = require('http');
const server = http.createServer((request, response)=>{
response.writeHead(200, {'Content-Type': 'text/plain'});
for (const [key, value] of Object.entries(request.headers)) {
response.write(`${key}: ${value}`);
}
response.end();
}).listen(3000);
+ 1
+ 1
Abdulaziz Abdurasul Object.entries(obj) returns both the object keys and values.
+ 1
Abdulaziz Abdurasul In case you're still curious about Object.entries() static method, check this link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
0
Use the for..in loop.
for (let key in object_name) {
let value = object_name[key];
}
0
XXX it doesn't work the way its expected
0
XXX Looping through object and printing name value each in new line ;
0
Russ try to creare a server with http module in Node js and console log the ruquest.headers
0
const http = require("http);
const server = http.createSeever(function(req,res){
console.log(req.headers);
});
0
Calviղ is there any other ways for not using Object.enties coz i have to submit this code in onle online web there is bot checking the code it will not accept this way
0
Calviղ and sorry Calvin u are very amazing guy i really appreciate u work🙏🙏 can u please in simple way explain the way and what this Objec.enties does ?