Node.js的框架
express 是第三方的php
const express=require('express'); const app=express(); const PORT=3000 const HOST='localhost' //建立路由/路由中间件 //目标http://localhost:8000/home app.get('/home',(req,res,next)=>{ // req:请求 // res:响应 // next:请求与响应之间的链接 res.send('平安夜') // res.json({ // name:'李兰生', // day:'平安夜' // }) }) //监听服务器 app.listen(PORT,HOST,()=>{console.log( `xpress建立的服务器在:http://${ HOST }:${PORT}`); })
expresscss
app.jshtml
const express=require('express'); const app=express(); const cors= require('cors'); const PORT=3000 const HOST='localhost' app.use(cors()) //建立路由/路由中间件 //目标http://localhost:8000/home app.get('/home',(request,response,next)=>{ //跨域请求头 // response.setHeader('Access-Control-Allow-Origin','*'); const http = require('http') const cheerio = require('cheerio') const options = { hostname: 'jx.1000phone.net', port: 80, path: '/teacher.php/Class/classDetail/param/rqiWlsefmajGmqJhXXWhl3ZiZ2Zn', method: 'GET', headers: { Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7', 'Cache-Control': 'no-cache', Connection: 'keep-alive', Cookie: 'PHPSESSID=ST-117984-IVZSfYMlr9YXvRfFRm-A1TimOeA-izm5ejd5j1npj2pjc7i3v4z', Host: 'jx.1000phone.net', Pragma: 'no-cache', Referer: 'http://jx.1000phone.net/teacher.php/Class/index', 'Upgrade-Insecure-Requests': 1, 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36', 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': 0 } } http.get(options, (res) => { /* res就是我获得的返回值 */ const { statusCode } = res; // 状态码 const contentType = res.headers['content-type']; // 获得的文件类型 res.setEncoding('utf8'); // 中文编码 let rawData = ''; // 真实数据 res.on('data', (chunk) => { rawData += chunk; });// 经过data事件将数据分片,而后逐片添加到rawData身上,好处就是当咱们执行每个分片的小任务时,至少给其余任务提供了可执行的机会 res.on('end', () => { // 表示结束 try { // 高级编程 错误捕获 const $ = cheerio.load( rawData ) let arr=[]; $('.student a').each(function ( index,itm ) { // console.log( $( this ).text() ) // 每个的内容 arr.push( { id:index+1, name:$( this ).text() }); }) response.json( arr); } catch (e) { console.error(e.message); } }); }).on('error', (e) => { console.error(`Got error: ${e.message}`); }); }) //监听服务器 app.listen(PORT,HOST,()=>{console.log( `xpress建立的服务器在:http://${ HOST }:${PORT}`); })
index.html前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> </head> <body> <button> 获取数据 </button> <br> <table> <thead> <tr> <td>编号</td> <td> 姓名 </td> </tr> </thead> <tbody> </tbody> </table> </body> <script> const baseURL='http://localhost:3000' $('button').on('click',function(){ // $.ajax({ // url:`${baseURL}/home`, // success(res){ // console.log(res); // } // }) $.ajax({ url:`${baseURL}/home`, success(res){ let str=``; for(var item of res){ str+=`<tr> <td>${item.id}</td> <td>${item.name}</td> </tr>` } $('tbody').html(str) } }) }) </script> </html>
express-generatornode
// 项目须要的第三方模块 var createError = require('http-errors');//记录错误信息 var express = require('express');//express的顶级库,提供espres api var path = require('path');//处理磁盘路径 var cookieParser = require('cookie-parser');//cookie var logger = require('morgan');//记录日志信息 //引入自定义的路由中间件 var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); //建立app对象 var app = express(); // 视图引擎设置 app.set('views', path.join(__dirname, 'views'));//处理view的绝对路径 app.set('view engine', 'ejs');//设置项目模板渲染引擎为ejs //经过app对象来使用中间件 app.use(logger('dev')); app.use(express.json());//为post请求作格式化 app.use(express.urlencoded({ extended: false }));//项目文件能够省略项目后缀 app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public')));//肯定项目资源静态目录指定为pubic //调用路由中间件 建立接口 app.use('/api', indexRouter); app.use('/api', usersRouter); // 捕获404并转发给错误处理程序(错误中间件) app.use(function(req, res, next) { next(createError(404)); }); //错误处理程序 app.use(function(err, req, res, next) { // 设置局部变量,只提供开发中的错误 res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // 渲染错误页面 res.status(err.status || 500); res.render('error'); }); module.exports = app;