创建基本的服务器
const express = require('express');
const indexRouter = require('./router');
const app = express();
const port = 3000;
app.use('/api', indexRouter);
app.listen(port, () => {console.log(`Server is running on http://localhost:${port}`);
});
创建路由文件
const express = require('express');
const router = express.Router();module.exports = router;
实现GET请求
router.get('/get', (req, res) => {const query = req.query;console.log(query, 'query')res.send({code: 0, msg: 'GET请求成功', data: query, });
});
实现POST请求
方式1:form-data,Express默认不会解析form-data,因为它通常用于文件上传,需要额外的处理。你可以使用multer这个中间件来处理multipart/form-data(也就是form-data)类型的请求。multer是专门为Express设计的,用于处理多部分/表单数据,这包括上传文件。
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
router.post('/upload', upload.single('file'), (req, res) => {const body = req.body;console.log(body, 'body')res.send({code: 0, msg: 'POST请求成功', data: body, });
});
方式2:urlencoded,想要获取url-encoded请求体的数据,需要引入对应的中间件。
app.use(express.urlencoded({extended: false}))
router.post('/post', (req, res) => {const body = req.body;console.log(body, 'body')res.send({code: 0, msg: 'POST请求成功', data: body, });
});
全部代码
index.js
const express = require('express');
const indexRouter = require('./router');
const app = express();
const port = 3000;
app.use(express.urlencoded({extended: false}))
app.use('/api', indexRouter);
app.listen(port, () => {console.log(`Server is running on http://localhost:${port}`);
});
router.js
const express = require('express');
const multer = require('multer');
const router = express.Router();
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
router.get('/get', (req, res) => {const query = req.query;console.log(query, 'query')res.send({code: 0, msg: 'GET请求成功', data: query, });
});
router.post('/upload', upload.single('file'), (req, res) => {const body = req.body;console.log(body, 'body')res.send({code: 0, msg: 'POST请求成功', data: body, });
});
router.post('/post', (req, res) => {const body = req.body;console.log(body, 'body')res.send({code: 0, msg: 'POST请求成功', data: body, });
});
module.exports = router;