Vue——前端框架,Node——JavaScript运行时环境,可以运行在服务器上,在小项目中node完全可以作为自己的服务器使用,目前学习node是为了完成毕业设计。
但是两者怎么联系在一起?因为两者本身存在跨域问题。以下简例解决问题。
首先先创建一个Vue项目Client,这里使用脚手架创建
主要代码如下
1 /**main.js*/ 2 import Vue from 'vue' 3 import App from './App' 4 import axios from 'axios' 5 Vue.prototype.$axios = axios; 6 7 axios.defaults.baseURL = '/api'; 8 9 Vue.config.productionTip = false; 10 11 /* eslint-disable no-new */ 12 new Vue({ 13 el: '#app', 14 components: { App }, 15 template: '<App/>' 16 });
1 /**App.vue*/ 2 <template> 3 <div> 4 2222 5 </div> 6 </template> 7 8 <script> 9 export default { 10 name: 'App', 11 mounted(){ 12 this.$axios({ 13 method:'get', 14 url:'/' 15 }).then(res => { 16 console.log( res ) 17 }) 18 }, 19 components: { 20 } 21 } 22 </script> 23 24 <style> 25 </style>
接着创建一个服务器Server
1 /**app.js*/ 2 3 const express = require('express'); 4 5 const app = express(); 6 7 app.get('/',function (req,res) { 8 res.send('hello express vue') 9 }); 10 11 app.listen(3000,function () { 12 console.log('server is running') 13 });
解决跨域问题,在Vue项目中,找的项目文件夹config/index.js
在proxyTable: {}中插入如下代码:
1 proxyTable: { 2 '/api': { // 匹配所有以 '/api'开头的请求路径 3 target: 'http://localhost:3000', // 代理目标的基础路径 4 changeOrigin: true, // 支持跨域 5 pathRewrite: {// 重写路径: 去掉路径中开头的'/api' 6 '^/api': '' 7 } 8 } 9 }
此外,在main.js中,添加一行 代码axios.defaults.baseURL = '/api'; ;
启动服务器, node app.js
启动前端项目, npm run dev
此时数据已经打印在控制台中
注意这里面 /api是你自定义的,写成什么都可以。target 设置你调用的接口域名和端口号。这里理解成用‘^/api’代替target里面的地址,后面组件中我们调接口时直接用api代替 。比如我要调用’http://localhost:3000/url‘,直接写‘/api/url’即可。
在main.js 设置 Vue.prototype.$axios = axios; 将axios写入Vue原型中,在全局的组件中就可以使用this.$axios.xxx的形式调用。
在main.js设置一个基础路径,这样你调用接口的时候可以不写api,直接写接口名称即可。axios.defaults.baseURL=”/api”。
配置完成,比如发送GET请求:this.$axios.get(‘/url’),简洁明了。