在DRF+Vue中使用axios访问接口

190 阅读1分钟

1.Django后端

数据库:

image.png

后端提供两个接口可进行访问:这是访问的路由形式

urlpatterns = [
    re_path('^index/$',views.index.as_view()),
    re_path('^check/(?P<pk>\d)$',views.check.as_view())
]

当以get方式访问 http://127.0.0.1:8000/test/index/时,显示所有数据的详细内容
当以post方式访问 http://127.0.0.1:8000/test/index/时,应传入数据才可添加记录

当以get方式访问 http://127.0.0.1:8000/test/check/(随机id)时,显示相应id的详细内容
当以put方式访问 http://127.0.0.1:8000/test/check/(随机id)时,应传入需要修改的数据方可对相应的id的记录进行修改
当以delete方式访问 http://127.0.0.1:8000/test/check/(随机id)时,删除对应id的记录

2.跨域设置

进行跨域设置 详见 跨域设置

3.vue中使用axios

image.png

request.js

// request.js

import axios from 'axios'
export function ins(){
  // 进行基础配置
  const instance = axios.create({
    // 在进行完跨域配置后,访问DRF提供的后端接口
    // 使用axios.create进行基本配置
    baseURL:'http://127.0.0.1:8000/',
    timeout:10000
  })
  return instance
}

home.js

import {ins} from './request'

// 查询全部
export function uselist(){
  return ins().get('test/index/')
}
// 增加操作,需要从实例中传入需要添加的数据
export function usepost(title,comment,collection){
  return ins().post('test/index/',{
    btitle:title,
    bcomment:comment,
    bcollection:collection
  })
}


// 修改操作,需要从实例中传入需要修改的数据
export function useput(id,title,comment,collection){
  return ins().put('test/check/'+String(id),{
      btitle:title,
      bcomment:comment,
      bcollection:collection
    }
  )
}
// 删除操作,需要从实例中传入id
export function usedelete(id){
  return ins().delete('test/check/'+String(id))
}

App.vue

  // 实际在App.vue中使用
  
  import {uselist,usepost,useput} from './network/home'
  ...
  
  created(){
    uselist().then(res => {
      // 获取到的res来自  http://localhost:3000/posts/1
      console.log(res);
    })
    usepost('秘密',123,123).then(res =>{
      console.log(res);
    })
    useput(9,'定心丸',12,56).then(res =>{
      console.log(res);
    })
    usedelete(10).then(res =>{
      console.log(res);
    })
  }