1、安装
- 用户量很多
- 适合高并发场景
- 可实现功能很多
- 安装 Node 稳定版本
- node -v 看版本
- app.js 里面写一句 使用 node app.js打印出来
2、http模块 url模块
- php 需要 apache Nginx的Http服务器
- nodejs不用
- 装一个 插件 node sn
- 安装完后 敲一个 node就可出来
// 引入http模块
var http = require("http");
// 请求和响应
http.createServer(function(req,res){
//设置响应头
res.writeHead(200,{"Content-Type":"text/plain"});
//表示页面输出什么 然后结束响应
res.end("Hello world");
}).listen(8081); //监听的端口
console.log('Server running at http://127.0.0.1:8081/')
- node app.js 执行
- http://127.0.0.1:8081/ 打印出内容
改动代码后需要 重启服务才会生效
- 当前
中文在页面上会乱码? 怎么解决?
res.writeHead(200,{"Content-Type":"text/plain;charset='utf-8'"});
//表示页面输出什么 然后结束响应
res.write("<head><meta charset='utf-8'></head>");
-
然而现实是 设置这样 页面还是乱码没有效果 怎么处理?
-
怎么获取页面的
Url呢 ?使用 req.url就可
console.log(req.url) //获取页面url
- 那么我怎么得到
name =zhangsan & age =20 只有右边的数据呢涉及url模块学习 核心是url.parse()可以得到url拆分后的内容
const { get } = require("http"); //引入http
const url = require("url"); // 引入url
var api = "http://www.baidu.com?name=zhangsan&age=20";
// console.log(url.parse(api,true))
var getValue = url.parse(api,true).query;
console.log(getValue)
console.log(`姓名:${getValue.name} -- 年龄:${getValue.age}`)
- 在原来的app.js;里面怎么
获取数据
// 引入http模块
var http = require("http");
const url = require("url")
// 请求和响应
http.createServer(function(req,res){
//设置响应头
res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"});
//表示页面输出什么 然后结束响应
res.write("<head><meta charset='utf-8'></head>");
console.log(req.url) //获取页面url
if(req.url != '/favicon.ico'){
var userinfo = url.parse(req.url,true).query;
console.log(`姓名:${userinfo.name}--年龄${userinfo.age}`)
}
res.end("Hello world 你好");
}).listen(8081); //监听的端口
console.log('Server running at http://127.0.0.1:8081/')
- 页面 这样测试