封装axios

新建helpers文件夹,新建request.ts文件

  1. import axios from 'axios'
  2. axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
  3. axios.defaults.baseURL = 'http://note-server.hunger-valley.com'
  4. axios.defaults.withCredentials = true // 跨域
  5. export default function request(url: string, type='GET', data={}){
  6. return new Promise((resolve, reject) => {
  7. const option:any = {
  8. url,
  9. method: type,
  10. validateStatus(status:number) {
  11. return (status >= 200 && status < 300) || status === 400
  12. }
  13. }
  14. if (type.toLowerCase() === 'get') {
  15. option.params = data
  16. } else {
  17. option.data = data
  18. }
  19. axios(option).then((res: { status: number; data: unknown }) => {
  20. if(res.status === 200) {
  21. resolve(res.data)
  22. } else {
  23. reject(res.data)
  24. }
  25. }).catch(() => {
  26. console.error({msg: '网络异常'})
  27. reject({msg: '网络异常'})
  28. })
  29. })
  30. }

使用封装好的接口

  1. import request from '@/helpers/request';
  2. request('auth/login', 'POST', {username: 'hunger', password: '123456'})
  3. .then(data => {
  4. console.log(data)
  5. })

调用auth接口查看登录状态

  1. import request from '@/helpers/request';
  2. request('auth')
  3. .then(data => {
  4. console.log(data)
  5. })

chrome在2020年3月份升级了安全策略,对于跨域请求如果想写入cookie,必须是https的网站才可以。对于http的网站,cookie写入总是失败。
解决办法:

  1. 修改package.json中的scripts为

    1. "scripts": {
    2. "serve": "vue-cli-service serve --https true",
    3. // ...
    4. },
  2. baseURL使用https

  3. Chrome浏览器输入chrome://flags/#allow-insecure-localhost 允许这个选项

参考

封装API接口

新建apis文件夹

  1. import request from '@/helpers/request';
  2. const URL = {
  3. REGISTER: '/auth/register',
  4. LOGIN: '/auth/login',
  5. LOGOUT: '/auth/logout',
  6. GET_INTO: '/auth'
  7. }
  8. interface Data {
  9. username: string,
  10. password: string
  11. }
  12. export default {
  13. register({username, password}:Data){
  14. return request(URL.REGISTER, 'POST', {username, password})
  15. },
  16. login({username, password}:Data){
  17. return request(URL.LOGIN, 'POST', {username, password})
  18. },
  19. logout(){
  20. return request(URL.LOGOUT)
  21. },
  22. getinfo(){
  23. return request(URL.GET_INTO)
  24. }
  25. }

调用接口

  1. import auth from '@/apis/auth'
  2. auth.get_info()
  3. .then(data => {
  4. console.log(data)
  5. })