node入门笔记

看了《node入门》http://www.nodebeginner.org/index-zh-cn.html。有些疑难点记下来。

在导出模块的时候给出的代码是这样的

 1 var http = require("http");
 2 
 3 function start() {
 4   function onRequest(request, response) {
 5     console.log("Request received.");
 6     response.writeHead(200, {"Content-Type": "text/plain"});
 7     response.write("Hello World");
 8     response.end();
 9   }
10 
11   http.createServer(onRequest).listen(8888);
12   console.log("Server has started.");
13 }
14 
15 exports.start = start;

  可以发现exports.start = start;但是不知道哪一个start是内部函数名哪一个是外部引用的名字。做了如下修改

var http = require("http");

function starrt() {
  function onRequest(request, response) {
    console.log("Request received.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
  }

  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}

exports.start = starrt;  //starrt 为内部函数名  star为外部调用的方法名

  发现exports.外部调用名  =  内部函数名;

关于url方法的调用

发现在文章中有 pathname = url.parse(req.url).pathname;

查了下API 知道 req.url  可以拿到所有的url 

例如:http://localhost:8888/start?foo=boo&hello=world   req.url = start?foo=boo&hello=world,即域名以后的路径。

我决定把url.parse(req.url)输出看看是什么

console.log(url.parse(req.url))

//以下为输出
{ protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?foo=boo&hello=world',
  query: 'foo=boo&hello=world',
  pathname: '/start',
  path: '/start?foo=boo&hello=world',
  href: '/start?foo=boo&hello=world' }

querystring.parse()这个方法可以把请求参数的键值对转换成json,

postData = user=asdsad&passwd=qweq;

querystring.parse(postData)之后变成 : { user: 'asdsad', passwd: 'qweq' };

原文地址:https://www.cnblogs.com/xjcjcsy/p/4196895.html