在node.js中解析查询字符串

时间:2021-07-08 02:07:11

In this "Hello World" example:

在这个“你好世界”的例子中:

// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

How can I get the parameters from the query string?

如何从查询字符串获取参数?

http://127.0.0.1:8000/status?name=ryan

In the documentation, they mentioned:

在文件中,他们提到:

node> require('url').parse('/status?name=ryan', true)
{ href: '/status?name=ryan'
, search: '?name=ryan'
, query: { name: 'ryan' }
, pathname: '/status'
}

But I did not understand how to use it. Could anyone explain?

但我不知道如何使用它。有人能解释一下吗?

Thanks in advance

谢谢提前

3 个解决方案

#1


96  

You can use the parse method from the URL module in the request callback.

您可以在请求回调中使用来自URL模块的解析方法。

var http = require('http');
var url = require('url');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  var queryData = url.parse(request.url, true).query;
  response.writeHead(200, {"Content-Type": "text/plain"});

  if (queryData.name) {
    // user told us their name in the GET request, ex: http://host:8000/?name=Tom
    response.end('Hello ' + queryData.name + '\n');

  } else {
    response.end("Hello World\n");
  }
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

I suggest you read the HTTP module documentation to get an idea of what you get in the createServer callback. You should also take a look at sites like http://howtonode.org/ and checkout the Express framework to get started with Node faster.

我建议您阅读HTTP模块文档,了解在createServer回调中会得到什么。您还应该查看诸如http://howtonode.org/和checkout这样的站点,以便更快地从节点开始。

#2


19  

There's also the QueryString module's parse() method:

还有QueryString模块的parse()方法:

var http = require('http'),
    queryString = require('querystring');

http.createServer(function (oRequest, oResponse) {

    var oQueryParams;

    // get query params as object
    if (oRequest.url.indexOf('?') >= 0) {
        oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));

        // do stuff
        console.log(oQueryParams);
    }

    oResponse.writeHead(200, {'Content-Type': 'text/plain'});
    oResponse.end('Hello world.');

}).listen(1337, '127.0.0.1');

#3


0  

node -v v9.10.1

节点- v v9.10.1

If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value

如果您试图直接控制日志查询对象,您将得到error TypeError:不能将对象转换为原始值

So I would suggest use JSON.stringify

所以我建议使用JSON.stringify

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);

    const path = parsedUrl.pathname, query = parsedUrl.query;
    const method = req.method;

    res.end("hello world\n");

    console.log(`Request received on: ${path} + method: ${method} + query: 
    ${JSON.stringify(query)}`);
    console.log('query: ', query);
  });


  server.listen(3000, () => console.log("Server running at port 3000"));

So doing curl http://localhost:3000/foo\?fizz\=buzz will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}

这样做curl http://localhost:3000 / foo \ ?fizz\=buzz将返回收到的请求:/foo +方法:GET +查询:{“fizz”:“buzz”}

#1


96  

You can use the parse method from the URL module in the request callback.

您可以在请求回调中使用来自URL模块的解析方法。

var http = require('http');
var url = require('url');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  var queryData = url.parse(request.url, true).query;
  response.writeHead(200, {"Content-Type": "text/plain"});

  if (queryData.name) {
    // user told us their name in the GET request, ex: http://host:8000/?name=Tom
    response.end('Hello ' + queryData.name + '\n');

  } else {
    response.end("Hello World\n");
  }
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

I suggest you read the HTTP module documentation to get an idea of what you get in the createServer callback. You should also take a look at sites like http://howtonode.org/ and checkout the Express framework to get started with Node faster.

我建议您阅读HTTP模块文档,了解在createServer回调中会得到什么。您还应该查看诸如http://howtonode.org/和checkout这样的站点,以便更快地从节点开始。

#2


19  

There's also the QueryString module's parse() method:

还有QueryString模块的parse()方法:

var http = require('http'),
    queryString = require('querystring');

http.createServer(function (oRequest, oResponse) {

    var oQueryParams;

    // get query params as object
    if (oRequest.url.indexOf('?') >= 0) {
        oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));

        // do stuff
        console.log(oQueryParams);
    }

    oResponse.writeHead(200, {'Content-Type': 'text/plain'});
    oResponse.end('Hello world.');

}).listen(1337, '127.0.0.1');

#3


0  

node -v v9.10.1

节点- v v9.10.1

If you try to console log query object directly you will get error TypeError: Cannot convert object to primitive value

如果您试图直接控制日志查询对象,您将得到error TypeError:不能将对象转换为原始值

So I would suggest use JSON.stringify

所以我建议使用JSON.stringify

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);

    const path = parsedUrl.pathname, query = parsedUrl.query;
    const method = req.method;

    res.end("hello world\n");

    console.log(`Request received on: ${path} + method: ${method} + query: 
    ${JSON.stringify(query)}`);
    console.log('query: ', query);
  });


  server.listen(3000, () => console.log("Server running at port 3000"));

So doing curl http://localhost:3000/foo\?fizz\=buzz will return Request received on: /foo + method: GET + query: {"fizz":"buzz"}

这样做curl http://localhost:3000 / foo \ ?fizz\=buzz将返回收到的请求:/foo +方法:GET +查询:{“fizz”:“buzz”}