这是我的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”:空}:
我使用chrome ARC以这种格式成功发布: username = test&password = Abcd1234&grant_type = password&client_id = null&client_secret = null
有人知道是什么问题吗?
答案 0 :(得分:0)
在main.js中尝试一下:
expressApp.use(bodyParser.json());
此外,不要在axios.js中使用url编码,而应使用json。将标头设置为此:
'content-type': 'application/json',