学习内容
- axios及二次分装;
- 解决vue开发环境下的跨域问题;
- 搭建简单的node.js服务器
一、 创建简单的node服务器
1、全局下载依赖
npm install -g express
npm install -g express-generator
2、创建服务器项目
express server --view=ejs
3、在 server/routes/index.js 中写一个接口
如:
router.get('/list', function(req, res, next) {
res.send({
a:1
})
});
4、重启 server
5、访问 http://localhost:3000/list
二、代理解决开发环境下的跨域
跨域问题出现情况
因为浏览器的安全机制:同源策略。
当两个页面的 url 的协议( http, https )、主机和端口号三者有一者不相同,就会产生跨域问题。
跨域报错信息:
Access to XMLHttpRequest at 'http://localhost:3000/list' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
// 代理解决"开发环境"下的跨域,在项目主目录下创建 vue.config.js
// vue.config.js
const { defineConfig } = require('@vue/cli-service');
medule.exports = defineConfig({
devServer:{
proxy: 'http://localhost:3000', // 代理的服务器地址
}
})
// 请求的时候只需要写端口后面的地址就可以
axios.get('/list');
三、axios简单的二次封装
axios参数分析:
axios({
url: '', // 地址
baseUrl: '', // 基地址
method: '', // 请求方式,默认 get
headers: {}, // 自定义请求头
params: {}, // get 请求的参数,也可以直接已 ?key=val 的方式写在 url 后面
data: {}, // post 请求的参数
timeout: 6000, // 请求超时时间
responseType: 'json', // 服务器返回的数据类型,默认 json
})
// src/utils/request.js
import axios from 'axios';
// 1. 创建 axios 对象
const instance = axios.create({
baseURL: 'http://localhost:3000',
timeOut: 6000,
})
// 2. 请求拦截器 ===> 控制前端传向后端的参数 [还没到后端响应]
instance.interceptors.request.use(function (config){
/*
* 操作请求时的数据等,如
* 登录判断,如果用户是登录状态,在headers中把用户的token传递给后端
*/
return config;
}, function (error){
return Promise.reject(error)
});
// 3.响应拦截器 ===> 后端响应数据
instance.interceptors.response.use(function (response){
// 对后端返回的数据进行处理
return response;
}, function (error) {
return Promise.reject(error);
});
// 最终返回对象
export default instance;
四、API解耦
创建js文件,如 src/api/config.js
// 1. 引入二次分装 axios 文件
import request from '@/utils/request';
// 请求接口
export function getList(){
return request({
url: '/list'
})
};
export function getData( options = {} ) {
return request({
url: 'url',
method: 'post',
data: options.data,
headers: options.headers
})
}
<script>
import { getList, getData } from '@/api/config';
export default {
created(){
getList().then(res => {
console.log(res)
})
getData({
data: { key: val },
headers: { "Content-Type": "application/json" }
}).then(res => {
console.log(res)
})
}
}
</script>
五、开发生产环境 (VUE)
开发阶段
代码开发阶段,使用 npm run serve 启动项目
生产阶段
npm run build之后部署到线上的项目
vue的环境变量
1) 创建环境变量文件
项目根目录创建:
.env.development ===> 开发环境
.env.production ===> 生产环境
2) .env 文件中属性名必须以 VUE_APP_ 开头
3) 调用 .env 文件中的变量
process.env.VUE_APP_XXX
通过 process.env.NODE.ENV 能够获取到当前是生产环境还是开发环境
能够解决的问题 1.由于 devServer:{proxy: 'url'} 只能解决开发环境下的跨域问题,所以到了生产环境 axios.get('/list') 访问的地址就变成了 file:///list, 所以在 axios 二次分装中需要根据环境变量配置 baseURL。
注:实力不够,写着只是总结自己当天学了什么。如有问题,请麻烦指出。