2017-08-02 163 views
0

以下是我的代碼。如何從環形結構化數據中讀取財產

var myHttp = require("http"); 
var url = require("url"); 
var qString = require("querystring"); 
var fs = require('fs'); 

var myEvents = require('./customEvents'); 

var myAppWebServer = myHttp.createServer(function(request, response){ 

     response.writeHead(405, {'content-type':'text/html'}); 

     console.log(request.headers); 

     response.end('{ "name":"my Name", "location":"xxx"}');   
}); 

myAppWebServer.listen(8080); 

當我使用console.log(request.headers)打印響應標題文本時,它會打印下面的數據。

{ 
    host: 'localhost:8080', 
    connection: 'keep-alive', 
    'x-os-version': 'Windows 7', 
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36', 
    'content-type': 'application/json', 
    location: 'bangalore', 
    'x-useragent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.86 Safari/537.36', 
    'x-enteringpage': 'http://localhost:8080/login', 
    accept: '*/*', 
    referer: 'http://localhost:8080/login', 
    'accept-encoding': 'gzip, deflate, br', 
    'accept-language': 'en-US,en;q=0.8', 
    cookie: '_ga=GA1.1.1554321962.1498024434; _gid=GA1.1.1406177709.1501568327' 
} 

我不知道如何在控制檯中打印'x-useragent'。我使用下面的語法,但拋出錯誤。

console.log(request.headers.x-useragent); 

有人可以幫忙。

+0

你剛剛打印了嗎? (Mozilla/5.0)(Windows NT 6.1; Win64; x64)AppleWebKit/537.36(KHTML,如Gecko)Chrome/59.0.3071.86 Safari/537.36' –

+0

@yiImz:我得到了引用錯誤。無法打印該值。 – user2613946

回答

0

與特殊字符Javascript對象鍵都用這樣的方式:

request.headers["x-useragent"]

You can access object properties in two ways:

objectName.propertyName

objectName [「propertyName」]

用chrome devtool快照編輯。

enter image description here

+0

我厭倦了你的語法。它將值打印爲未定義。 – user2613946

+0

你把'console.log(request.headers.x-useragent);'改爲'console.log(request.headers [「x-useragent」]);'但不工作?這對我來說毫無意義。 – Val

+0

再次嘗試---它可以在Chrome devtool控制檯中使用。看到我編輯的帖子。 – Val