在这个"Hello World"示例中:

// 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/");

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

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

在文件中,他们提到:

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

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

推荐答案

您可以在请求回调中使用URL module中的parse方法.

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);

我建议你阅读HTTP module documentation,了解一下你在createServer回调中得到了什么.您还应该查看http://howtonode.org/Express framework这样的网站,以便更快地开始使用Node.

Node.js相关问答推荐

try 使用Puppeteer抓取Twitter时数组空

容器端口是容器内 node 应用程序的端口吗?

NodeJS中的Vertex AI GoogleAuthError

已知NPM无法在node.js V12上运行的问题

在对象的嵌套数组中使用$lookup,创建多个记录作为响应,mongodb

为什么 Cors 在 NodeJS 中不起作用

如何修改这个flake.nix,这样我就不用每次加载环境都加载nix包了

访问 Mongoose 查询之外的变量

Mongodb聚合传递一个匹配的数组和一个不匹配的数组

为什么我的react 表单不能正常工作?

使用 Node.js 在 MongoDB 中搜索

使用中的端口代码:'EADDRINUSE',即使在 kill 命令之后

无服务器无法获取所有记录事件对象验证失败?

在 PassportJS 中使用多种本地策略

node.js 是否支持yields ?

如何在客户端使用 node.js 模块系统

带有加密的nodejs中的SALT和HASH密码

通过 POST 请求将数据从 node.js 服务器发送到 node.js 服务器

续集findbyid不是一个函数,但显然findAll是

如何从 Node.js 应用程序Ping?