【问题标题】:how to access query string with Node.js如何使用 Node.js 访问查询字符串
【发布时间】:2016-03-09 11:33:14
【问题描述】:

我是 Node.js 的新手。 我编写了简单的 Node.js 程序来打印 hello world。 而且效果很好。

现在当我同时传递查询字符串时,它会给出错误

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

【问题讨论】:

标签: html node.js query-string


【解决方案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/');

网址

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

【讨论】:

    猜你喜欢
    • 2017-05-15
    • 2013-07-06
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 2014-09-04
    相关资源
    最近更新 更多