express 中使用post方法
Express中默认都使用body-parser作为请求体解析post数据,这个模块也能解析:JSON、Raw、文本、URL-encoded格式的请求体。
首先在项目目录安装body-parser:
npm install body-parser
在app.js中使用该插件
const express = require('express')
const bodyParser = require('body-parser')
const router = require('./router')//引用模块
const app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// 全局 中间件 解决所有路由的 跨域问题
app.all('*',function (req,res,next) {
res.header('Access-Control-Allow-Origin','*')
res.header('Access-Control-Allow-Headers','X-Requested-With,Content-Type')
res.header('Access-Control-Allow-Methods','GET,POST,OPTIONS')
next()
})
app.use(router)
app.listen(3000,function () {
console.log('服务器启动成功')
console.log('http://127.0.0.1:3000')
})
router目录下index.js文件:
const {Router} = require('express')
const path = require('path')
const router = new Router()
router.get('/',function (req,res){
res.send({
msg: 'hi node express'
})
})
router.post('/login',function (req,res){
// req: 客户端 携带的信息
// console.log(req.query)
// console.log(req.params)
console.log(req.body)
// console.log(req.get('Origin'))
// console.log(req.url)
// res 服务端 发送给 客户端的信息(数据)
// res.send({
// msg: 'login 接口'
// })
// res.end('不会自动转换数据 容易乱码')
// res.download('./static/dj.jpg') // 相对地址
// res.sendFile(path.resolve('static','dj.jpg')) // 绝对地址
// res.redirect('https://www.shiguangkey.com/')
// res.redirect('https://www.shiguangkey.com/')
res.set('sadsadsadsafdgsfadgfsdfsd','789')
res.send({
msg: 'set演示'
})
})
module.exports = router
使用postman进行测试接口:
成功!!!