1204
- 简历中写上做过一个社区文章展示的网站,自己起一个名字,里面自己写了什么东西,是个人练手的项目。不是公司的,根据网站提供的 api 去做的一个练手的东西,不是项目经验。
- 在 created 和 mounted 这两个发请求触发我们的 axios 都差不多,这两个都是同步的生命钩子,created 执行完了, mounted 就执行。axios 发请求都是异步的,请求的结果肯定在这两个人之后执行,但是通常习惯用 created 发请求。他们两者又有什么区别呢?
后台相关的 1204(1:40:00)
vue.shequ
:不带跨域的话 vue 社区提供的 api 资源请求不回来。- 什么叫做跨域:协议 http,域名 localhost: ,端口号 8080, 三者任意一种不同就认为是跨域。
- 怎么支持跨域?我自己去写跨域
前端接口跨域的问题解决方法有两种
- 使用 JQuery 提供的 jsonp,只有 jquery 能用
- 服务器代理解决(代理就是挂载到服务器上,给服务器做代理)
- 但是代理的话需要 挂载在服务器上,本地的服务器叫 localhost:8080
- 我们现在的代理是 vue 的语法做的代理,跟我自己在服务器上做的就不太一样。
封装一个 axios.js
import axios from "axios";
// https://vue-js.org/api/v1 改成 https://vue-js.com/api/v1
// 以指定将被用在各个请求的配置默认值
axios.defaults.baseURL = "/api";
axios.interceptors.response.use((res) => res.data);
// 因为每次请求回来的数据里面都会有一个 data 添加响应拦截器 对响应数据做点什么
// 为了区分自己的封装 就把 axios 变成 $axios
const $axios = axios;
// 然后导出出去,那个组件想用就导入使用
export default $axios;
// 这个是给全部组件添加的,这个更省事,因为请求的数据放在 vuex 中了,就不需要在全局中引入 axios 。
// Vue.prototype.$http = axios;
vue.config.js
module.exports = {
devServer: {
proxy: {
"/api": {
// 这个是代理的地方
target: "https://vue-js.com/api/v1",
ws: true, //缓存
changeOrigin: true,
// 路径重写 axios 用 /api 发请求,然后就把 /api 设置为空, 就指到 target: "https://vue-js.com/api/v1",
pathRewrite: {
"^/api": "",
},
},
},
},
};
然后想在哪里发请求就可以了
$axios.get(`/topic/xxxx)
后台接口跨域的问题解决方法
- 借助 node + express 搭建简易后台服务器,并且添加一些数据
- express 是 node 的包,快速搭建服务器
// import express from "express";
// import 是 ES6 语法的导入导出,只对 vue src 里面的生效,对 src 外面的不生效。
// 1. node 方式导入 express
const express = require("express");
const bodyParser = require("body-parser");
// 2. 创建 app 服务器VUE
const app = express();
app.use(bodyParser.json());
// 3. 启动服务器并设置端口号 在命令行工具中实行 node server.js
app.listen(3000, function () {
console.log("服务器已经启动 在端口号 http://localhost:3000/");
});
// 4. 获取数据并设置跳转的页面(现在还不支持跨域) 请看 5.xxxx
// res 是响应,响应类似 json 的文件,意思就是传入一个 json的一个文件,然后 req 是依赖解析 req.body post发送的数据解析出来的对象
// app.get('./menus) ==> http://localhost:3000/menus 是基于服务器地址的 不同于 axios.get('http://localhost:3000')
app.post("/menus", (req, res) => {
const { text } = req.body;
let menuList;
if (text === "管理员") {
menuList = [
{ pid: -1, name: "购物车", id: 1, auth: "cart" },
{ pid: 1, name: "购物车列表", id: 4, auth: "cartlist" },
{ pid: 4, name: "彩票", id: 5, auth: "lottery" },
{ pid: 4, name: "商品", id: 6, auth: "goods" },
{ pid: -1, name: "商店", id: 2, auth: "store" },
{ pid: -1, name: "个人中心", id: 3, auth: "me" },
];
} else if (text === "普通用户") {
menuList = [
{ pid: -1, name: "购物车", id: 1, auth: "cart" },
{ pid: -1, name: "商店", id: 2, auth: "store" },
{ pid: -1, name: "个人中心", id: 3, auth: "me" },
];
}
// 接收前端传过来的参数
res.json({
menuList,
});
});
// 5. 跨域请求
// all 所有请求 * 是所有地址 next() 跟路由守卫的通行差不多 ,next 就代表我让你通行。 res 是响应
app.all("*", (req, res, next) => {
// 响应头的设置,我的后台支持跨域请求
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "*");
res.header("Content-Type", "application/json;charset=utf-8");
next();
});