express后端渲染页面+restful api暴露接口

    xiaoxiao2022-07-07  194

    后端渲染页面有以下步骤: (以渲染一个http:localhost:8000/login 页面为例)

    进入app.js 首先引入路由配置文件, var loginRouter = require( './routes/login' ) //再创建路由级中间件 app.use('/', loginRouter) 在routes中创建login.js文件 ,里面写的是数据 //引入express模块 const express = require('express') const router = express.Router() // router.get( 路由路径, 中间件) router.get( '/login',function( req,res,next ) { res.render('login',{ username: 'yyb', password: 123 }) }) //不能忘记暴露路由 module.exports = router 在vies文件夹中找到对应的ejs模板,用ejs语法引用数据

    4.npm start 运行项目

    restful api 暴露接口并在insomnia测试

    进入app.js 首先引入路由配置文件, var dxtRouter = require( './routes/dxt' ) //再创建路由级中间件 app.use('/', dxtRouter) 在routes中创建dxt.js文件 ,里面写的是数据,可以选择restful api 各种方式暴露数据 1.get方法 router.get( '/dxt',function( req,res,next ) { //第一种,用JSON.stringify()转一次,在对应ejs写<%= dxt%> // 并且选择在测试工具的Form Query输入测试 // console.log(req.query) let { username,password } = req.query res.render('dxt',{ dxt:JSON.stringify({ username, password }) }) // 第二种发送方式直接用res.json({}) // res.json({ // ret: true, // username: 'aabb', // password: 12321 // }) }) 2.post方法 // 在测试工具先选择post在直接选择Form 直接输入测试 router.post( '/dxt', function ( req, res, next) { let { username,password } = req.body console.log(req.body) res.render('dxt',{ dxt:JSON.stringify({ username, password }) }) }) put router.put('/',function ( req,res,next ) { res.render('mine',{ mine: JSON.stringify({ ret: true, text: '增加' }) }) }) delete router.delete('/',function ( req,res,next ) { res.render('mine',{ mine: JSON.stringify({ ret: true, text: '删除' }) }) }) all 应用场景: get post put 等都行 千万记住,项目上线一定要改回来 // router.all('/',function( req,res,next ) { // res.render('mine',{ // mine: JSON.stringify({ // ret: true, // text: 'all' // }) // }) // })
    最新回复(0)