nodejs-1

nodejs

nodejs是javascript的运行环境,让javascript可以开发后端程序,几乎能实现其他后端语言能实现的所有功能。

HTTP

// 引入http模块
var http = require('http');
/**
 * http.createServer:创建web服务
 * request:获取URL传过来的信息
 * response:给浏览器响应信息
 */

http.createServer(function (request, response) {
  // 打印url
  console.log(request.url);
  // 设置响应头
  // 状态码是200,文件类型
  response.writeHead(200, {"Content-Type": "text/html;charset='utf-8'"});
  // 写入内容
  response.write('hihihihihi~');
  // 表示给页面上输出一句话并结束响应
  response.end('Hello World');
}).listen(8081);   // 端口

console.log('Server running at http://127.0.0.1:8081/');

自己手写一个

const http = require('http');

http.createServer((req, res) => {
  console.log(req.url);

  /**
   * 设置响应头
   * 状态码:200
   * 文件类型:html
   * 字符集:utf-8
   */
  res.writeHead(200, {
    // charset: 'utf-8'    解决乱码
    "content-type": "text/html; charset: 'utf-8'"
  });
  // 写入内容
  // 如果这块写入的是中文的话,会出现乱码  =>  浣犲ソ nodejs demo
  // 这是因为响应头里面设置了 utf-8 ,但在页面里面没有设置,两个不一致,所以会出现乱码

  // 这个时候就需要在页面里面通过 res.write 来设置一下 utf-8,解决乱码
  res.write("<head><meta charset='UTF-8'></head>")

  res.write('你好 nodejs demo');
  // 结束响应
  res.end();
  // 设置端口
}).listen(8000);

console.log('http://127.0.0.1:8000');

URL

  • url.parse 解析url
  • url.format(urlObject) 是url.parse()操作的逆向操作
  • url.resolve(from, to) 添加或替换地址

url.parse 解析url

在后面加上一个true

const url = require('url');

var api = "http://www.baidu.com?name=doris&age=18";

var getValue = url.parse(api, true).query;
console.log(getValue,"getValue");
console.log(`姓名:${getValue.name}   年龄:${getValue.age}`);

  • url模块的应用

将客户端网页里的url做一个修改后打印一下req.url

  • 客户端网页的url
    http://127.0.0.1:8000/?name=doris&age=18
  • 服务器打印出来的内容

说明:这快的这个 /favicon.ico 是网页上面的那个图标

获取url传递的数据并解析
const http = require('http');
const url = require('url');

http.createServer((req, res) => {
  res.writeHead(200, {
    "content-type": "text/html; charset: 'utf-8'"
  });
  res.write("<head><meta charset='UTF-8'></head>")

  console.log(req.url);
  if (req.url !== '/favicon.ico') {
    var userInfo = url.parse(req.url, true).query;
    console.log(userInfo);
    console.log(`姓名:${userInfo.name}   年龄:${userInfo.age}`);
  }

  res.end();
}).listen(8000);
console.log('http://127.0.0.1:8000');

模块及自定义模块

commonjs

javascript标准定义的API是为了构建基于浏览器的应用程序,并没有制定一个用于更广泛的应用程序标准库。

commonjs规范的提出,主要是为了弥补当前javascript没有标准库的缺陷,它的终极目标就是实现一个类似python或Java或ruby语言的标准库,而不只是让javascript停留在小脚本程序的阶段。
上面就是在bb…

commonjs就是模块化的标准,nodejs就是commonjs(模块化)的实现。

nodejs中的模块化

nodejs的应用是由模块组成的,采用commonjs模块规范。
nodejs中的模块分为两大类

  • 核心模块:node提供的模块。http模块、URL模块、FS模块可以直接引入使用
  • 文件模块:用户编写的模块。需要我们自己定义的模块,在运行时动态加载的
自定义模块

我们可以把公共的功能抽离成为一个单独的js文件作为一个模块,默认情况下这个模块里面的方法或属性外部是没有办法访问的。如果要让外部可以防伪的话,就必须在模块里面通过exports或者module.exports暴露属性或方法。

在需要使用这些模块的文件中,通过require的方式来引入这个模块,这时就可以使用模块里面暴露的方法和属性了。

下面来试一下基本的写法

  • /module/tool.js
function formatApi(api){
  return "http://www.baidu.com/"+api;
}

exports.formatApi = formatApi;
  • app.js
const http = require('http');
const tools = require('./module/tools.js');

http.createServer((req, res) => {
  res.writeHead(200, {
    "content-type": "text/html; charset: 'utf-8'"
  });
  res.write("<head><meta charset='UTF-8'></head>")
  var api = tools.formatApi('api/focus');
  res.write(api);
  res.end();
}).listen(8000);

console.log('http://127.0.0.1:8000');

下面来看一下不同的暴露方法

第一种
  • module/request.js
var obj = {
  get: function () {
    console.log("从服务器获取数据");
  },
  post: function () {
    console.log("提交数据");
  }
}
exports.way = obj;
  • app.js
var request = require('./module/request');
console.log(request.way);   
 //这个时候拿到的就是这样的: { get: [Function: get], post: [Function: post] }
第二种
  • module/request.js
var obj = {
  get: function () {
    console.log("从服务器获取数据");
  },
  post: function () {
    console.log("提交数据");
  }
}
// 1.如果把所有的东西都封装在一个对象中的话,用下面这种
module.exports = obj;


// 2.如果有很多方法的话,用下面这中
exports.get = function () {
  console.log("从服务器获取数据");
}

exports.post = function () {
  console.log("提交数据");
}
  • app.js
var request = require('./module/request');

// console.log(request);        // { way: { get: [Function: get], post: [Function: post] } }
// console.log(request.way);    // { get: [Function: get], post: [Function: post] }

console.log(request);           // { get: [Function: get], post: [Function: post] }
// 这时就直接通过  request.get() / request.post()来调用
不同的引入方法
  • node_modules/index.js
exports.get = function () {
  console.log("从服务器获取数据");
}

exports.post = function () {
  console.log("提交数据");
}
  • app.js
// 1
const axios = require('./node_modules/axios/index');
axios.get(); // 从服务器获取数据

// 2
const axios = require('axios/index');
axios.get(); // 从服务器获取数据
axios.post(); // 提交数据

// 3
//node_modules 中定义的模块,可以不写完全的路径,而直接用 require('文件夹名称') 就可以引入该文件夹下面对应的 index.js 文件
const axios = require('axios');
axios.get(); // 从服务器获取数据
axios.post(); // 提交数据

⚠️ node.js 默认会找node_modules对应模块里面的index.js

新建 node_modules/db/db.js 文件

这时,在node_modules/db/目录下是 db.js 而不是 index.js, 那在 app.js 中怎么引入呢?

可以在该目录下通过 npm init --yes来强制生成一个papackage.json文件

注意上面的项目入口文件

  • node_modules/db/db.js
exports.find = function () {
  console.log("查找数据");
}

exports.add = function () {
  console.log("增加数据");
}

接下来及可以通过下面的代码进行引入了

  • app.js
// 单纯这样引入的话会报错,因为不是node_module下面的index.js
// 所以需要先去 demo04_xxx/node_modules/db/ 目录下生成package.json文件
var db = require('db');

db.add();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值