问题描述
我正在与NuxtJS一起练习ExpressJS。我期望从axios
POST请求获取数据,但是在req.body
和req.params
上总是空着。以下是我的配置和摘要
nuxt.config.js
...
serverMiddleware: [
{ path: '/api',handler: '~/api/index.js' }
],...
api / index.js
const express = require('express')
// Create express instance
const app = express()
// Require API routes
const staticDeploy = require('./routes/static-deploy')
// Import API Routes
app.use(staticDeploy)
// Export express app
module.exports = app
// Start standalone server if directly running
if (require.main === module) {
const port = process.env.PORT || 3001
app.listen(port,() => {
console.log(`API server listening on port ${port}`)
})
}
api / routes / static-deploy.js
const { Router } = require('express')
var CryptoJS = require('crypto-js')
const router = Router()
router.post('/static-deploy',(req,res) => {
console.log('req: ' + req.url) // Returns "req: /static-deploy/"
console.log('req: ' + req.body) // Returns "req: undefined"
console.log('req: ' + JSON.stringify(req.params)) // Returns "req: {}"
console.log('req headers: ' + JSON.stringify(req.headers)) // Returns "req headers: {"accept":"application/json,text/plain,*/*","content-type":"application/json;charset=utf-8","user-agent":"axios/0.19.2","content-length":"12","host":"localhost:3000","connection":"close"}"
const STATIC_DEPLOY_AUTH = {
username: 'virus',password: 'pass1234',secret: 'utf81234'
}
var bytes = CryptoJS.AES.decrypt(req.body,STATIC_DEPLOY_AUTH.secret)
var decryptedBody = bytes.toString(CryptoJS.enc.Utf8)
if (
decryptedBody.username === STATIC_DEPLOY_AUTH.username &&
decryptedBody.password === STATIC_DEPLOY_AUTH.password
) {
console.log('Authentication successful')
res.send('Ok')
}
})
module.exports = router
节点CLI命令
const CryptoJS = require('crypto-js')
const axios = require('axios')
const ciphertext = CryptoJS.AES.encrypt(
'{"username": "virus","password": "pass1234"}','utc81234'
).toString()
axios.post('http://localhost:3000/api/static-deploy/',ciphertext).catch(error => {
console.log('Error: ' + error)
})
解决方法
解决方法是在 api / index.js 中添加以下代码段:
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
中所述