封装axios
新建helpers文件夹,新建request.ts文件
import axios from 'axios'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.baseURL = 'http://note-server.hunger-valley.com'
axios.defaults.withCredentials = true // 跨域
export default function request(url: string, type='GET', data={}){
return new Promise((resolve, reject) => {
const option:any = {
url,
method: type,
validateStatus(status:number) {
return (status >= 200 && status < 300) || status === 400
}
}
if (type.toLowerCase() === 'get') {
option.params = data
} else {
option.data = data
}
axios(option).then((res: { status: number; data: unknown }) => {
if(res.status === 200) {
resolve(res.data)
} else {
reject(res.data)
}
}).catch(() => {
console.error({msg: '网络异常'})
reject({msg: '网络异常'})
})
})
}
使用封装好的接口
import request from '@/helpers/request';
request('auth/login', 'POST', {username: 'hunger', password: '123456'})
.then(data => {
console.log(data)
})
调用auth接口查看登录状态
import request from '@/helpers/request';
request('auth')
.then(data => {
console.log(data)
})
chrome在2020年3月份升级了安全策略,对于跨域请求如果想写入cookie,必须是https的网站才可以。对于http的网站,cookie写入总是失败。
解决办法:
修改package.json中的scripts为
"scripts": {
"serve": "vue-cli-service serve --https true",
// ...
},
baseURL使用https
- Chrome浏览器输入
chrome://flags/#allow-insecure-localhost
允许这个选项
封装API接口
新建apis文件夹
import request from '@/helpers/request';
const URL = {
REGISTER: '/auth/register',
LOGIN: '/auth/login',
LOGOUT: '/auth/logout',
GET_INTO: '/auth'
}
interface Data {
username: string,
password: string
}
export default {
register({username, password}:Data){
return request(URL.REGISTER, 'POST', {username, password})
},
login({username, password}:Data){
return request(URL.LOGIN, 'POST', {username, password})
},
logout(){
return request(URL.LOGOUT)
},
getinfo(){
return request(URL.GET_INTO)
}
}
调用接口
import auth from '@/apis/auth'
auth.get_info()
.then(data => {
console.log(data)
})