如何使用 Node.js 访问查询字符串
how to access query string with Node.js
我是 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
这可能对您有所帮助
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
我是 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
这可能对您有所帮助
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