启动服务端
- 根目录下新建mock文件夹
- login.json
{
"code": 0,
"message": "登录成功",
"data": {
"name": "张三",
"token": "ququ"
}
}
- index.js
npm i express --save
const express = require('express')
const app = express()
//接口数据
const login = require('./data/login.json')
// http://localhost:3300/login接口会返回上面数据
app.get('/login', (req, res) => {
// const user = url.parse(req.url, true).query.user
// console.log(111, user);
res.send(login)
})
app.listen(3300, () => {
console.log('服务器启动');
})
- mock文件夹右键打开终端运行 node index.js,则会打印服务器启动即成功
- 在浏览器打开http://localhost:3300/login 即可看到返回数据
- 页面中掉接口的跨域问题:proxy
// vue.config.js
module.exports = {
lintOnSave: false, //关闭eslint
devServer: {
proxy: {
//代理域名'/api' === 'http://localhost:3300'
'/api': {
target: 'http://localhost:3300',
// secure: false, // 默认情况下,不接受运行在 HTTPS 上
pathRewrite: { '^/api': '' }, //重写api
ws: false,
changeOrigin: true //允许跨域
}
}
},
}
- 页面中掉接口
//api/index.js
import axios from '../utils/http'
export function login(name) {
return axios.get("/api/login?name=" + name)
}
//Login.vue
import { login } from "../api/index";
async login() {
const data = await login(this.name);
console.log(data);
alert(data.data.name);
}