写一个小接口,用postman测试接口是否可行😝😝javascript
import express from 'express' import config from './config' import router from './router' import queryString from 'querystring' const app = express() app.use('/node_modules', express.static(config.node_modules_path)) app.use('/public', express.static(config.public_path)) // 解析处理表单 POST 请求体中间件 app.use((req, res, next) => { // 因为表单 POST 请求可能会携带大量的数据,因此在进行请求提价的时候会分为屡次提交 // 具体分为多少次进行提交不必定,取决于数据量的大小 // 在 Node 中,对于处理这种不肯定的数据,使用事件的形式处理 // 这里能够经过监听 req 对象的 data 事件,而后经过对应的回调处理函数中的参数 chunk 拿到每一次接收到的数据 // data 事件触发多少次,不必定 // 当数据接收完毕以后,会自动触发 req 对象的 end 事件,而后就能够在 end 事件中使用接收到的表单 POST 请求体 let data = '' req.on('data', chunk => { data += chunk }) req.on('end', () => { // 手动给 req 对象挂载一个 body 属性,值就是当前表单 POST 请求体对象 // 在后续的处理中间件中,就能够直接使用 req.body 了 // 由于在同一个请求中,流通的都是同一个 req 和 res 对象 req.body = queryString.parse(data) next() }) }) // 挂载路由容器(路由容器中组织了网站功能处理路由中间件) app.use(router) app.listen(3000, () => { console.log('server is running at port 3000...') })
import express from 'express' // 建立一个路由容器,将全部的路由中间件挂载给路由容器 const router = express.Router() router.get('/', (req, res, next) => { res.render('index.html') }) router.post('/advert/add', (req, res, next) => { // 接口客户端提交的数据 console.log(req.body) }) // 经过 export default 暴露的接口成员不能定义的同时直接暴露 // 最好先定义,再暴露 // export default 能够直接暴露字面量 {} 123 export default router