Express 是一个保持最小规模的灵活的 Node.js Web 应用程序开发框架,为 Web 和移动应用程序提供一组强大的功能。
const express = require("express");
const app = express();
// 使用中间件:
// 使代码更简洁,共享数据
// 中间件按先后顺序依次执行,需要在中间件最后添加next()
// 1.注册中间件需要放置在请求之前
// 2可以连续调用多个中间件
// 3执行完每一个中间件后需要添加next()
// 4执行完next之后不要在写业务逻辑
// 5.多个中间件之间可以共享req和res
// const func = function(req,res,next){
// console.log("我是第二个中间件");
// req.names = "zs";
// next();
// }
// app.use(func)
// app.use(function(req,res,next){
// console.log("我是第二个中间件");
// res.age = 18;
// console.log(req.names);
// next();
// })
// app.get("/",(req,res,next)=> {
// res.send(`${req.names}---${res.age}返回get请求数据`);
// console.log("触发get请求");
// next();
// })
// app.get("/user",(req,res,next)=> {
// res.send(`${req.names}---${res.age}返回get中user请求数据`);
// console.log("触发get中user请求");
// // next();
// })
// const func = function(req,res,next){
// console.log("我是第一个中间件");
// req.names = "zs";
// next();
// }
// const myFunc = function(req,res,next){
// console.log("我是第二个中间件");
// console.log(req.names);
// next();
// }
// app.get("/",func,myFunc,(req,res)=>{
// res.send("get返回局部中间件");
// console.log("get返回局部中间件");
// })
// app.post("/",[func,myFunc],(req,res)=>{
// res.send("post请求成功");
// console.log("post请求成功");
// })
// 通过app.use或app.get或app.post进行实例,应用级中间件
// app.use((req,res,next)=>{
// console.log("应以级中间件");
// next();
// })
// app.get("/",(req,res)=>{
// res.send("get请求成功");
// })
// 通过绑定在app.Router,路由级中间件
// const routes = express.Router();
// routes.use((req,res,next)=>{
// console.log("路由级中间件");
// next();
// })
// app.use(routes);
// app.get("/",(req,res)=>{
// res.send("get请求成功");
// })
// 用于捕捉异常错误的中间件,错误级别中间件
// app.get("/",(req,res)=>{
// res.send("请求失败");
// throw new Error("服务器内部请求错误");
// })
// app.use((err,req,res,next)=>{
// console.log(`错误中间件捕捉的信息为--${err.message}`);
// })
// CORS 跨域资源共享,中间件
// npm i cors安装跨域资源包
// app.use(cors());
app.get("/",(req,res)=>{
console.log("get请求成功");
// res.setHeader("Access-Control-Allow-Origin","*")
// res.setHeader("Access-Control-Allow-Methods","*")
// res.send({
// status:200,
// msg:"get请求成功",
// data:req.query
// });
// const data = {name: 'zs', age: 20};
// const str = req.query.callback;
// console.log(JSON.stringify(data));
// res.send(`${str}(${JSON.stringify(data)})`)
// res.send(`${req.query.callback}("get请求成功")`)
const str = {
name:req.query.name,
age:req.query.age
}
console.log(req.query);
res.send(`${req.query.callback}(${JSON.stringify(str)})`)
})
app.listen("8080",()=>{
console.log("服务启动成功 127.0.0.1:8080");
})