'nuxt axios.post request with empty body

I'm trying to get nuxt with axios working. I do the following post request (store/index.js):

login({ commit }, { username, password }) {
  const data = JSON.stringify({
    password
  , username
  })
  console.log('store login ', username, password)
  this.$axios.post('http://localhost:3000/api/login', data)  
  .then(res => {
    commit('SET_USER', res.data)
  })
  .catch(error => {
    console.log(error.response)
  })
}

My backend looks like this (api/auth.js):

const express           = require('express')
const session           = require('express-session')
const body_parser       = require('body-parser')
const app               = express()
const router            = express.Router()

app.use(body_parser.json())
app.use(body_parser.urlencoded({ extended: true }))
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: false
}))

router.post('/login', (req, res) => {
  console.log('try to login ', req.body)
  if (!req.body)
    return res.status(401).json({ message: 'No body' })
  if (req.body.username === 'demo' && req.body.password === 'demo') {
    req.session.auth_user = { username: 'demo' }
    console.log('logged in')
    return res.json({ username: 'demo' })
  }
  res.status(401).json({ message: 'Bad credentials' })
})

My Problem is, that the req.body is always undefined. But in the error message I can see, that the params are sent. (config.data)

enter image description here

Does anybody has an idea what I'm missing? I use body-parser and checked everything 100 times. I guess it's something total obvious, but I can't see it.

My nuxt.config.js:

module.exports = {
  ...
  modules: [
    '@nuxtjs/axios'
  , '@nuxtjs/auth'
  ],
  router: {
    middleware: ['auth']
  },
  serverMiddleware: ['@api/auth']
  ...
}


Solution 1:[1]

Probably you take this error also. This is caused by cors policy.

Access to XMLHttpRequest at 'http://localhost:3000/.......' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

same problem occured on my project.

in server index.js change line

const host = process.env.HOST || 'localhost'

and nuxt.config.js

axios: {
baseURL: 'http://localhost:YOUR_PORT'
 },

Solution 2:[2]

You must define bodyParser in router.

router.use(express.json())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Sefa Çiçekli