nodejs,,一些基本操作--server。js
1.解决中文乱码问题:
const http = require('http')
const server = http.createServer((req, res) => {
// 设置字符编码 - 设置文本的解析形式
// 200 表示本次请求是成功的
// text/html ---- 解析标签输出
// text/plain ---- 转义标签输出 ---- 原样输出
// nodejs服务器 默认是 text/html
res.writeHead(200, {
'Content-Type': 'text/plain;charset=utf-8'
})
res.write('<h1>hello world</h1>')
res.write('<h2>您好</h2>') // 如果出现中文字符,默认会乱码 ---- 设定字符编码
res.end()
})
server.listen(3000)
console.log('your server is runing at http://localhost:3000')
// ???? 打开控制台 -》 NETWORK,刷新页面,发现有2个请求 --- 要的是一个请求 ---- 过滤不需要的请求2.
2.解析网址(自己设置的网址)
// http
// 解析网址 url
/**
* 完整的URL地址的解析字段
┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│ href │
├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
│ protocol │ │ auth │ host │ path │ hash │
│ 协议 │ │ ├─────────────────┬──────┼──────────┬────────────────┤ │
│ │ │ │ hostname │ port │ pathname │ search │ │
│ │ │ │ 域名 │ 端口 │ 路由 ├─┬──────────────┤ │
│ │ │ │ │ │ │ │ query │ │
" https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string #hash "
│ │ │ │ │ hostname │ port │ │ │ │
│ │ │ │ ├─────────────────┴──────┤ │ 参数 │ 哈希值│
│ protocol │ │ username │ password │ host │ │ │ │
├──────────┴──┼──────────┴──────────┼────────────────────────┤ │ │ │
│ origin │ │ origin │ pathname │ search │ hash │
├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
│ href │
└────────────────────────────────────────────────────────────────────────────────────────────────┘
*
*/
const url = require('url') const urlStr = "http://localhost:3000/login?username=wudaxun&password=123456" // url.parse(urlStr[, boolean]) --- 将字符串类型的网址转换成对象 const obj = url.parse(urlStr,true) // console.log(obj) /**
* Url {
protocol: 'http:', // 协议
slashes: true,
auth: null, // 作者
host: 'localhost:3000', // 域名 + 端口
port: '3000', // 端口
hostname: 'localhost', // 域名
hash: null, // 哈希值
search: '?username=wudaxun&password=123456', // ? + 参数
query: 'username=wudaxun&password=123456', // 字符串类型的参数
pathname: '/login', // 路由
path: '/login?username=wudaxun&password=123456', // 路由 + ? + 参数
href: 'http://localhost:3000/login?username=wudaxun&password=123456' // 完整的地址
}
*/ console.log(obj.query) // username=wudaxun&password=123456
console.log(obj.query.username) //wudaxun
console.log(obj.query.password) //123456
2.1.过滤图标设置图标
/**
* 过滤图标 、设置路由
*/
const http = require('http');
const url = require('url'); // 获取前端请求的信息 --- url.parse() 字符串的url转成对象 const server = http.createServer((req, res) => {
if (req.url !== '/favicon.ico') { // 过滤图标的请求
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf-8'
}) const urlObj = url.parse(req.url, true) // true 将参数类型的字符串转成对象 // // write函数不能输出对象,可以输出字符串 ---- 对象转字符串
// res.write(JSON.stringify(urlObj)) // 拿路由
// const pathname = urlObj.pathname
const { pathname } = urlObj; res.write('<h1>您好,世界!</h1>' + pathname); res.end();
}
}); server.listen(3000); console.log('your server is running at http://localhost:3000'); // querystring username=wudaxun&password=123456&sex=1&age=18 转成 对象
3.querystrng将参数类型的字符串转换成对象类型
/**
* querystring
* 将参数类型的字符串转换成对象类型
*
* username=wudaxun&password=123456
*
* ===>
*
* { username: wudaxun, password: 123456 }
*/
const querystring = require('querystring') const queryStr = 'username=wudaxun&password=123456&age=18' // querystring.parse(queryStr) *---- 将字符串类型的参数 转换成 对象 const obj = querystring.parse(queryStr) console.log(obj) /***
* {
username: 'wudaxun',
password: '123456',
age: '18'
} 总结:
实际开发过程中并不需要使用 querystring,建议使用 url.parse(str, true) url.parse()的第二个参数为true可转对象,其原理就是 querystring.parse()
*/ // ??? 已知的网页字符串可以搞定,那么如果是用户输入的网址呢?
4.解析网址(服务器获取的网址)
const http = require('http')
const url = require('url')
const server = http.createServer((req, res) => {
if (req.url !== '/favicon.ico') {
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf-8'
})
const urlStr = req.url // /login?username=wudaxun&password=123456
const obj = url.parse(urlStr, true).query // { username: 'wudaxun', password: '123456' }
const { username, password } = obj
res.write(`用户名:${username}`)
res.write(`密码: ${password}`)
res.end()
}
})
server.listen(3000)
// 登录 注册表单 不要使用 & --- 丢失数据
/**
* 如果用户输入 /home 那么输出 首页
* 如果用户输入 /kind 那么输出 分类
* 如果用户输入 /cart 那么输出 购物车
* 如果用户输入 /user 那么输出 个人中心
*/
fs(file-system)
/**
* fs ---- file system
* 后端语言的标志:
* 文件的读写
*/ // 文件的读操作
// fs.readFile(path, 'utf-8', (err, data) => {}) const fs = require('fs') fs.readFile('./01node介绍.html', 'utf-8', (err, data) => {
if (err) {
console.log(err)
} else {
console.log(data)
}
})
在服务器打开别的网页:
const http = require('http')
const fs = require('fs')
const server = http.createServer((req, res) => {
if (req.url !== '/favicon.ico') {
res.writeHead(200, {
'Content-Type': 'text/html;charset=utf-8'
})
fs.readFile('./12test.html', 'utf-8', (err, data) => {
if (err) throw err // 遇到错误,抛出异常,代码不再继续执行
res.write(data)
res.end()
})
}
})
server.listen(3000)
/**
* 如果用户输入 /home 那么输出 首页.html
* 如果用户输入 /kind 那么输出 分类.html
* 如果用户输入 /cart 那么输出 购物车.html
* 如果用户输入 /user 那么输出 个人中心.html
*/
nodejs,,一些基本操作--server。js的更多相关文章
- NodeJS路由(server.js + router.js)
手动路由... server.js 创建http服务器,解析pathname,传递给router处理. var http = require("http"); var url = ...
- Nodejs入门-基于Node.js的简单应用
服务端JavaScript 众所周知的,JavaScript是运行在浏览器的脚本语言,JavaScript通常作为客户端程序设计语言使用,以JavaScript写出的程序常在用户的浏览器上运行.直至N ...
- Nodejs 操作 Sql Server
Nodejs 操作 Sql Server Intro 最近项目需要爬取一些数据,数据有加密,前端的js又被混淆了,ajax请求被 hook 了,有些复杂,最后打算使用 puppeteer 来爬取数据. ...
- Node聊天程序实例06:server.js
作者:vousiu 出处:http://www.cnblogs.com/vousiu 本实例参考自Mike Cantelon等人的<Node.js in Action>一书. server ...
- nodejs 批处理运行 app.js
1.直接执行run.bat文件 以下的内容为批处理文件run.bat中的内容,批处理命令中NODE_PATH为Node.js的安装路径. 使用express 生成的项目.app.js为 ...
- 解决新版本webpack vue-cli生成文件没有dev.server.js问题
新版本webpack生成的dev.server.js 在webpack.dev.conf.js中 webpack.dev.conf.js const axios = require('axios') ...
- node+express 中安装nodemon实时更新server.js
每次启动node server.js,有一个缺点,每次server.js文件有改动时,必须重新执行指令node server.js,新的代码才会起作用 解决方案1 全局安装 npm install s ...
- nodejs报错 events.js:72 throw er; // Unhandled 'error' event
var http = require('http'); var handlerRequest = function(req,res){ res.end('hello');}; var webServe ...
- 【nodejs】使用Node.js实现REST Client调用REST API
最近在产品中开发基于REST的API接口,结合自己最近对Node.js的研究,想基于它开发一个REST Client做测试之用. 通过初步研究,Node.js开发HTTP Client还是挺方便的. ...
- NodeJs 实时压缩 项目js文件
+ 1. 下载nodejs : "http://nodejs.org/". + 2. 以administrator权限打开cmd.+ 3. cmd路径定位到要压缩的目录: &quo ...
随机推荐
- 【LeetCode】——分割回文串II
继续与动态规划斗智斗勇... 132. 分割回文串 II - 力扣(LeetCode) (leetcode-cn.com) 分析:记f[i]表示将字符串s[0:i]分割的最小次数.我们需要将列举出在[ ...
- c++ 构造名字不足的0补齐
stringstream ss; ss << setfill('0') << setw(10) << i; vstrImageFilenames[i] = strP ...
- Leetcode209
209. Minimum Size Subarray Sum i , s , l = 0, 0, 0 for j in range(len(nums)): ...
- springboot启动图标banner
将springboot项目中的banner.txt文件替换成下面代码即可 ${AnsiColor.BRIGHT_YELLOW} ┏━┓ ┏━┓ ┏┛ ┻━━━━━┛ ┻┓ ┃ ┃ ┃ ━ ┃ ┃ ┳┛ ...
- springboot项目控制台日志不是彩色的原因
采用springboot的方式启动,而不是application的方式启动,即可
- 【基础知识】C++算法基础(快速排序)
快速排序: 1.执行流程(一趟快排): 2.一趟快排的结果:获得一个枢纽,在此左边皆小于此数,在此右边皆大于此数,因此可以继续使用递归获得最终的序列.
- 探秘ThreadLocal
一 类结构 主要是set(T), get(), remove()方法 二 TheadLocal是什么时候创建的 threadLocal的初始化, lazy creating, 用到的时候(get 或 ...
- idea初学
IDEA 什么是IDE IDEA官网 idea中文设置:打开右上角设置选择设置,选择Plugins ,搜索Chinese,安装插件后重启即可 IDEA基础语法 注释 编写代码量多时,项目结构复杂,需要 ...
- [Cisco] IOS NAT Load-Balancing for Two ISP Connections
interface FastEthernet0 ip address dhcp ip nat outside ip virtual-reassembly ! interface FastEtherne ...
- SQLyog 13.1.1.0注册码证书秘钥
注册信息: Name:(用户名随意) License Key: Professional: 8e053a86-cdd3-48ed-b5fe-94c51b3d343c Enterprise: a4668 ...