NuxtJS ServerMiddleware Express API中加入了请求正文

问题描述

我正在与NuxtJS一起练习ExpressJS。我期望从axios POST请求获取数据,但是在req.bodyreq.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 }))

https://aslamdoctor.com/blog/simple-crud-app-using-express-nuxtjs-using-servermiddleware-part-1-2/239

中所述

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...