代码均在js文件中, 运行: $node xxx.js
注意输入命令行时要进入当前文件夹,
$pwd为当前路径,再$cd 路径
nodejs
1. http
const http = require('http');
const server = http.createServer();
server.listen('3000',()=>{
console.log('listening on http://localhost:3000');
//打印出来则创建成功
});
server.on('request', (req,res)=>{
//当request请求,调用该函数
res.end('hello world');
//response返回字符串给浏览器
//这里不能用send,send方法由express框架提供
});
2.fs
const fs = require('fs');
//路径写成'./a.txt或者a.txt'为当前文件夹下的a.txt
//不能写成'/a.txt',/表示根目录(C:\,D:\等等)
fs.writeFile('./a.txt','aaaa', 'utf-8', (err) =>{
if(err) throw err;
console.log('写入内容:aaaa, utf-8格式, err为null');
});
fs.readFile('./a.txt', 'utf-8', (err, data)=>{
if(err) throw err;
console.log("a.txt内容为:" + data);
//a.txt内容为:aaaa
});
express框架
1.
const express = require('express');
const app = express();
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
//http://localhost:3000
});
//app.use((req,res,next)=>{...}):如果前面不加路径,那么所有路径访问前都会执行一遍该函数
//http://localhost:3000/index
app.use('/index', (req, res, next)=>{
console.log('1:/index的use中间件请求');
next();
//需要加next(),不然下面的/index路径函数不会执行
});
//发送get请求时执行
app.get('/index',(req, res)=>{
console.log('2:get请求');
res.send('hello world');
});
//发送post请求时执行
// app.post('/',(req, res)=>{
// console.log('post请求');
// });
2.router
子路由
//2.js
const router = require('./3')
const express = require('express')
const app = express();
app.listen(3000,() => {
console.log('http://localhost:3000');
})
app.use('/a', router);
//http://localhost:3000/a/index返回信息
//3.js
const express = require('express')
const router = express.Router()
router.get("/index", (req,res,next)=>{
res.send("我是index");
console.log(1);
})
module.exports = router;
2.js
const express = require('express');
const app = express();
const router = require('./3');
app.listen(3000, () => {
console.log('http://localhost:3000');
});
app.use('/', router);
//访问http://localhost:3000,先调用router
app.get('/', () => {
console.log('第二');
});
3.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => {
console.log('第一')
res.send('Hello World!');
next();
//中间件一定要记得next
});
module.exports = router;