node vue项目开发之前后端分离实战记录

2020-06-17 07:05:41易采站长站整理

<router-view/>
</div>
</template>

这样就可运行了

前后端分离

习惯了用node做全栈开发,现在用vue-webpack做前端开发,node做后端开发也挺爽的,前后端实现了分离。

启动后端接口


cd back
cnpm install
npm run dev

启动前端服务器


cd front
cnpm install
npm start

进入登录页面,点击登录,控制台打印访问成功的信息,并成功跳转到helloworld页面

前后端通信

vue-resource

安装vue-resource 并在main.js中引用


import VueResource from 'vue-resource'
Vue.use(VueResource)

在config/index.js 配置 proxyTable代理服务器


proxyTable: {
'/api/**': {
target: 'http://localhost:3000',
pathRewrite: {
'^/api': '/api'
}
}
}

使用


this.$http.get('api/apptest')
.then((response) => {
// 响应成功回调
console.log(response)
}).catch(e => {
// 打印一下错误
console.log(e)
})
}

缺点:在开发环境下没有问题,但是在生产环境下请求后端接口不成功

axios

首先配置axios,在src下新建一个http.js


import axios from ‘axios'
axios.defaults.timeout = 5000
axios.defaults.baseURL = 'http://localhost:3000'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
export default axios

在main.js中引入


import axios from './http'
Vue.prototype.axios = axios
new Vue({
el: '#app',
router,
axios,
template: '<App/>',
components: { App }
})

使用

get方法


login () {
// 获取已有账号密码
this.axios.get('/apptest')
.then((response) => {
// 响应成功回调
console.log(response)
// this.$router.go({name: 'main'})// 不管用
this.$router.push({name: 'HelloWorld'})
}).catch(e => {
// 打印一下错误
console.log(e)
})
}

post方法


register () {
console.log(this)
// 获取已有账号密码
let params = {
user: this.userinfo.account,
password: this.userinfo.password,
directionId: this.userinfo.directionId
}
this.axios.post('/signup', params)
.then((response) => {
// 响应成功回调
console.log(response)
}).catch(e => {
// 打印一下错误