【问题标题】:vue app axios post data to express backend receiving undefinedvue app axios post data to express 后端接收 undefined
【发布时间】:2019-04-04 18:39:31
【问题描述】:

这是我的 vue 应用的 main.js,这个应用在 localhost:8080 上运行并尝试将数据发布到 localhost:8081 (express.js)

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from './backend/vue-axios'
import BootstrapVue from 'bootstrap-vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

Vue.use(BootstrapVue)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  axios,
  template: '<App/>',
  components: { App }
})

Login.vue 组件

<template>
  <div class="login-wrapper border border-light">
    <form class="form-signin" @submit.prevent="login">
      <h2 class="form-signin-heading">Please sign in</h2>
      <label for="inputEmail" class="sr-only">Email address</label>
      <input v-model="email" type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
      <label for="inputPassword" class="sr-only">Password</label>
      <input v-model="password" type="password" id="inputPassword" class="form-control" placeholder="Password" required>
      <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      email: '',
      password: ''
    }
  },
  methods: {
    login () {
      this.axios.post('http://localhost:8081/login', { username: this.email, password: this.password, grant_type: 'password', client_id: null, client_secret: null })
        .then(request => this.loginSuccessful(request))
        .catch(() => this.loginFailed())
    },
    loginSuccessful (req) {
      if (!req.data.token) {
        this.loginFailed()
        return
      }

      localStorage.token = req.data.token
      alert(req.data.token)
      this.error = false

      this.$router.replace(this.$route.query.redirect || '/authors')
    },
    loginFailed () {
      this.error = 'Login failed!'
      delete localStorage.token
    }
  }
}
</script>

<style lang="css">
body {
  background: #605B56;
}

.login-wrapper {
  background: #fff;
  width: 70%;
  margin: 12% auto;
}

.form-signin {
  max-width: 330px;
  padding: 10% 15px;
  margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
  margin-bottom: 10px;
}
.form-signin .checkbox {
  font-weight: normal;
}
.form-signin .form-control {
  position: relative;
  height: auto;
  -webkit-box-sizing: border-box;
          box-sizing: border-box;
  padding: 10px;
  font-size: 16px;
}
.form-signin .form-control:focus {
  z-index: 2;
}
.form-signin input[type="email"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}
</style>

/src/backend/vue-axios/axios.js

import axios from 'axios'

const API_URL = 'http://localhost:8081/restrictedArea/enter'

export default axios.create({
  baseURL: API_URL,
  headers: {
    'content-type': 'application/x-www-form-urlencoded',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token'
    // 'Authorization': 'Bearer ' + localStorage.token
  }
})

/src/backend/vue-axios/index.js

import Vue from 'vue'
import VueAxios from 'vue-axios'

import axios from './axios'

Vue.use(VueAxios, axios)

export default axios

index.js(后端 express.js)

//MARK: --- REQUIRE MODULES

const port = 8081
const mySqlConnection = require('./databaseHelpers/mySqlWrapper')
const accessTokenDBHelper = require('./databaseHelpers/accessTokensDBHelper')(mySqlConnection)
const userDBHelper = require('./databaseHelpers/userDBHelper')(mySqlConnection)
const oAuthModel = require('./authorisation/accessTokenModel')(userDBHelper, accessTokenDBHelper)
const oAuth2Server = require('node-oauth2-server')
const express = require('express')
const expressApp = express()
var cors = require('cors')
expressApp.use(cors())
expressApp.oauth = oAuth2Server({
  model: oAuthModel,
  grants: ['password'],
  debug: true
})

const restrictedAreaRoutesMethods = require('./restrictedArea/restrictedAreaRoutesMethods.js')
const restrictedAreaRoutes = require('./restrictedArea/restrictedAreaRoutes.js')(express.Router(), expressApp, restrictedAreaRoutesMethods)
const authRoutesMethods = require('./authorisation/authRoutesMethods')(userDBHelper)
const authRoutes = require('./authorisation/authRoutes')(express.Router(), expressApp, authRoutesMethods)
const bodyParser = require('body-parser')

//MARK: --- REQUIRE MODULES

//MARK: --- INITIALISE MIDDLEWARE & ROUTES

//set the bodyParser to parse the urlencoded post data
expressApp.use(bodyParser.urlencoded({ extended: true }))

//set the oAuth errorHandler
expressApp.use(expressApp.oauth.errorHandler())

//set the authRoutes for registration and & login requests
expressApp.use('/auth', authRoutes)

//set the restrictedAreaRoutes used to demo the accesiblity or routes that ar OAuth2 protected
expressApp.use('/restrictedArea', restrictedAreaRoutes)

//MARK: --- INITIALISE MIDDLEWARE & ROUTES
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.sendStatus(200);
} else {
next();
}
};

expressApp.use(allowCrossDomain);
//init the server
expressApp.listen(port, () => {

   console.log(`listening on port ${port}`)
})

expressApp.post('/login',function(req,res){
  var username=req.body.username;
  var password=req.body.password;
  console.log("User name1 = "+username+", password is "+password);
  res.end("yes");
});

控制台输出:

listening on port 8081
User name1 = undefined, password is undefined
User name1 = undefined, password is undefined

Axios 以这种格式发布,我在 chrome 控制台中找到了它:{"username":"hkvega01@gmail.com","password":"123","grant_type":"password","client_id":null ,"client_secret":null}:

我使用 chrome ARC 以这种成功的格式发布: username=test&password=Abcd1234&grant_type=password&client_id=null&client_secret=null

谁知道问题出在哪里?

【问题讨论】:

  • 你能在 /login 处理程序中记录 req 的全部内容吗?
  • @Jim B. 是的,我发现了类似 body: { '{"username":"test@gmail.com","password":"123","grant_type":"password" ,"client_id":null,"client_secret":null}': '' },但是这里发帖太长了
  • 我在您的服务器代码中没有看到 json bodyparser...

标签: express vue.js axios


【解决方案1】:

在 main.js 中试试这个:

expressApp.use(bodyParser.json());

另外,不要在 axios.js 中使用 url-encoding,而是使用 json。将您的标题设置为此:

'content-type': 'application/json',

【讨论】:

  • 刚刚添加,但我只能获取 req.body ({ '{"username":"test@gmail.com","password":"123","grant_type":"password" ,"client_id":null,"client_secret":null}': '' }) 但不是 req.body.username
猜你喜欢
  • 2019-06-20
  • 2022-01-23
  • 2019-12-30
  • 2020-10-26
  • 2020-06-11
  • 1970-01-01
  • 2021-12-15
  • 2020-07-21
  • 2019-08-28
相关资源
最近更新 更多