2013-04-02 102 views
0

在我的應用程序中,我需要將動態數據發佈到我的主頁面(mani頁面意味着如果我在瀏覽器中運行我的url(localhost:3456)意味着將在該頁面中顯示一頁)。我可以如何發佈這些數據。我已經嘗試過,但是我無法發佈數據。任何人都可以幫助我解決這個問題。如何在Node js中發佈數據

app.js

 var http = require('http'); 
    var server = http.createServer(function(req, res){ 
        res.writeHead(200, ['Content-Type', 'text/plain']); 
        res.write('Hello '); 
        res.end('World'); 
        }); 
    server.listen(3456); 

postdata.js

var data={"errorMsg":{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-0402T11:50:22.167Z"} 
var options = { 
       host: 'localhost', 
       port: 3456, 
       path: '/', 
       method: 'POST', 
       data:data, 
       header: { 
          'content-type': 'application/json', 
          'content-length': data.length  
         } 
       }; 

var http=require('http'); 
var req; 
req = http.request(options, function(res) { 
    var body; 
    body = ''; 
    res.on('data', function(chunk) { 
    body += chunk; 
    }); 
return res.on('end', function() { 
    console.log('body is '+body); 
    }); 
    }); 
req.on('error', function(err) { 
    console.log(err); 

}); 

req.write(data); 
req.end(); 
+2

這將不勝感激,如果你會花時間去格式化在請求其他人尋求幫助之前,以可讀的方式(正確縮進)對您的代碼進行編碼。 –

+0

@BretCopeland您好我已格式化我的code.Please檢查這一個 – sachin

回答

-1

你有與節點一起安裝明示,如果是的話,你可以設置REST API的,你可以在你的jQuery使用它們,動態綁定數據。請嘗試看看 http://expressjs.com/

希望這會有所幫助。

+0

好吧,但我想用http服務器 – sachin

-1

兩件事。第一:

var data={"errorMsg:{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-0402T11:50:22.167Z"} 

缺少一個雙引號,所以它是無效的語法...因此爲什麼語法高亮有麻煩。

二:

req.write(data); 

應該是:

req.write(JSON.stringify(data)); 

編輯:

基於您的評論,我想你可能會問如何從一個身體閱讀HTTP POST請求(你的問題非常含糊)。如果是這樣,Node.js API中已經有很好的文檔記錄。沿線的東西:

var server = http.createServer(requestHandler); 
server.listen(3456); 

function requestHandler (req, res) { 
    req.setEncoding('utf8'); 
    var body = ''; 
    req.on('data', function (chunk) { body += chunk; }); 
    req.on('end', function() { 
     res.writeHead(200, {'Content-Type': 'text/plain'}); 
     res.end('The body of your request was: ' + body); 
    }); 
} 

如果這不是你要求的,你需要澄清你的問題。像'主頁'這樣的術語沒有意義,除非你明確地定義了它們是什麼以及預期結果是什麼。

+0

嗨複製我的代碼我犯了一些錯誤我的數據是{「errorMsg」:{「errno」:34,「代碼「:」ENOENT「,」路徑「:」missingFile.txt「},」date「:」2013-04-03T05:29:15.521Z「}它已經轉換成JSON字符串。我需要顯示這個JSON字符串我的主要網頁我怎麼能做到這一點。 – sachin

+0

看看編輯是你在說什麼。 –

+0

mani頁面意味着如果我在瀏覽器中運行我的url(localhost:3456)意味着將在該頁面中顯示一個頁面。 – sachin

-1
//this is a string 
var jsonString = '{"errorMsg":{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-04-03T05:29:15.521Z"}'; 

//this is an object 
var jsonObj = {"errorMsg":{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-04-03T05:29:15.521Z"}; 

注:在單引號字符串

request.write(chunk, [encoding])需要塊作爲任何緩衝或字符串(參見:http://nodejs.org/api/http.html#http_request_write_chunk_encoding