在这个"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相关问答推荐

为什么我的表单数据在我的POST请求中作为应用程序/json发送,为什么它返回错误请求错误?

编辑Mongoose中的对象嵌套数组

Express Web 服务器部署到 prod 但 GET 返回超时错误

Redis Typescript 删除方法类型转换

我如何在nodejs中的路由之间交换令牌

如何使用 $PATH 变量在系统中全局自动安装 bash 脚本?或者重写脚本到node

在路由上使用中间件时,Nodejs Express 应用程序失败

npm install 在 Mac 上的 Node-gyp 构建错误

带有事件网格的 Azure 函数在没有 ngrok 的情况下在本地运行

如何使用来自前一阶段的另一个数组的聚合mongoose 在数组中添加字段

使用 .pipe(res) 向客户端发送音频不允许您搜索?

通过 npm 导入 Sass

带有 node.js 和 express 的基本网络服务器,用于提供 html 文件和assets资源

node_modules 中 .bin 文件夹的用途是什么?

用于排除多个文件的 node.js glob 模式

为什么模块级返回语句在 Node.js 中起作用?

Passport 的 req.isAuthenticated 总是返回 false,即使我硬编码 done(null, true)

处理快速异步中间件中的错误

将 Heroku App 连接到 Atlas MongoDB 云服务

从我之前部署的 firebase 控制台获取代码