2016-03-09 21 views
0

我是Node.js的新手。 我寫了簡單的Node.js程序來打印hello world。 它工作正常。如何使用Node.js訪問查詢字符串

現在,當我通過與沿查詢字符串,然後它給出了一個錯誤

Node.js的

var http = require("http"); 

http.createServer(function (request, response) { 

    // Send the HTTP header 
    // HTTP Status: 200 : OK 
    // Content Type: text/plain 
    response.writeHead(200, {'Content-Type': 'text/plain'}); 

    // Send the response body as "Hello World" 
    response.end('Hello World\n'+request.q); 
}).listen(8081); 

// Console will print the message 
console.log('Server running at http://127.0.0.1:8081/'); 

查詢從瀏覽器

http://127.0.0.1:8081/?q=MrX 

它給

Hello World 
undefined 
+1

嘗試request.body –

+0

http://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-表達-JS-上節點-JS?RQ = 1 – Pogrindis

回答

1

這個可以幫助你

var http = require("http"); 
    url = require("url"); 
http.createServer(function (request, response) { 

    // Send the HTTP header 
    // HTTP Status: 200 : OK 
    // Content Type: text/plain 
    response.writeHead(200, {'Content-Type': 'text/plain'}); 

    // Send the response body as "Hello World" 
    var _get = url.parse(request.url, true).query; 
    response.end('Here is your data: ' + _get['data']); 
// response.end('Hello World\n'); 
}).listen(8081); 

// Console will print the message 
console.log('Server running at http://127.0.0.1:8081/'); 

URL

http://127.0.0.1:8081/?data=MrX