使用rest_framework寫api接口的一些注意事項(axios發送ajax請求)

使用rest_framework寫api接口的一些注意事項(axios發送ajax請求)

1. 類繼承GenericAPIView,定義queryset

印象深入的事:
因爲原來對於繼承關係不太清楚,寫接口 APIView/泛指GenericAPIView不太關注queryset
沒有設置渲染器:默認 [JSONRenderer,BrowsableAPIRenderer]
BrowsableAPIRenderer,內部檢查當前視圖函數是否有 get_queryset,若有則會調用。未設置,則斷言異常。vue

2. 全部視圖都有功能:添加到配置文件

好比統一渲染器,解析器等ios

3. URL統一規則

url後加不加/等,都要統一ajax

4. 序列化 

- 簡單:fk/o2o/choice -> source
- 複雜:m2m/gfk -> SerializerMethodFieldnpm

在序列化類中定義字段時,對於一些簡單的外鍵、一對一字段或choice字段能夠使用source方法獲取想要的值json

而複雜一些的多對多字段等能夠使用自定義方法axios

複製代碼
class CourseSerializer(ModelSerializer):
    category = serializers.CharField(source='sub_category.name')
    xx = serializers.CharField(source='get_course_type_display')
    price_policy = serializers.SerializerMethodField()
    class Meta:
        model = models.Course
        fields = ['id', 'name','category','xx','price_policy']

    def get_price_policy(self, obj):
        price_policy_list = obj.degreecourse_price_policy.all()
        return [{'id': row.id, 'price': row.price, 'period': row.get_valid_period_display()} for row in
                price_policy_list]
複製代碼

5. cors

跨域請求能夠經過中間件添加相應的響應頭,一些參數還能夠寫到settings中api

複製代碼
class Cors(MiddlewareMixin):
    def process_response(self, request, response):
        response['Access-Control-Allow-Origin'] = ','.join(settings.CORS_ORIGIN_LIST)
        if request.method == 'OPTIONS':
            response['Access-Control-Allow-Methods'] =  ','.join(settings.CORS_METHOD_LIST)
            response['Access-Control-Allow-Headers'] = ','.join(settings.CORS_HEADER_LIST)
            response['Access-Control-Allow-Credentials'] = 'true'

        return response
複製代碼

使用axios發送ajax請求

首先要下載axios跨域

npm install axios --save

而後在main.js中導入,並使用Vue.prototype.axios=axios使this.axios=axios方法,讓咱們能夠在後面使用this.axios使用它app

 

複製代碼
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/store'
import axios from 'axios'

Vue.prototype.$store = store
Vue.prototype.$axios = axios
axios.defaults.headers['Content-Type'] = "application/json"

Vue.config.productionTip = false
複製代碼

這裏axios.defaults.headers['Content-Type'] = "application/json"的意思是後續的axios發送請求時請求頭中都會帶有Content-Type='application/json',ajax中也能作相應的設置,以下cors

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        xhr.setRequestHeader("Content-Type", "application/json");
    }
});

使用

複製代碼
init(){
  // 發送Ajax
  var that = this
  this.$axios.request({
    url: this.$store.state.apiList.course,
    method:'GET',
    params:{
      course_type:1
    }
  }).then(function (arg) {
    console.log('then',arg)
    that.courseList =arg.data.data
  }).catch(function (arg) {
    console.log('catch',arg.response)
  })
}
複製代碼

經過axios.request方法發起ajax請求,參數url是發送的地址,method是發送方法,params是url中的參數,若是要發送請求體中的參數則使用data

then至關於ajax中的success,catch至關於error

相關文章
相關標籤/搜索