前台(AngularJS)后台(django)对接工作总结

一、跨域访问受限问题处理:

问题现象:

跨域访问问题

问题处理:

  • 安装django-cors-headers:
sudo pip install django-cors-headers
  • 配置文件修改:
diff --git a/Server/Server/settings.py b/Server/Server/settings.py
index 4657df3..feca1d7 100644
--- a/Server/Server/settings.py
+++ b/Server/Server/settings.py
@@ -38,11 +38,13 @@ INSTALLED_APPS = [
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'coluslife',
+    'corsheaders',
 ]
 MIDDLEWARE = [
     'django.middleware.security.SecurityMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
+    'corsheaders.middleware.CorsMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
@@ -50,6 +52,11 @@ MIDDLEWARE = [
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
 ]
+CORS_ORIGIN_WHITELIST = (
+    '127.0.0.1:8000',
+    '127.0.0.1:9000',
+)
+
+CORS_ORIGIN_ALLOW_ALL = True
 ROOT_URLCONF = 'Server.urls'

二、bootstrap-table接受的数据结构跟django返回不一致问题处理:

问题现象:

  • bootstrap-table接受的数据结构:
# 不分页结构:
[
    {
        "id": 0,
        "name": "Item 0",
        "price": "$0"
    },
    {
        "id": 1,
        "name": "Item 1",
        "price": "$1"
    },
    {
        "id": 2,
        "name": "Item 2",
        "price": "$2"
    }
]
# 分页结构:
{
    "total": 200,
    "rows": [
        {
            "id": 0,
            "name": "Item 0",
            "price": "$0"
        },
        {
            "id": 1,
            "name": "Item 1",
            "price": "$1"
        }
    ]
}
  • django返回的数据结构:
{
  "meta": {
    "limit": 50,
    "next": null,
    "offset": 0,
    "previous": null,
    "total_count": 1
  },
  "objects": [
    {
      "resource_uri": "/api/v1/oplog/NATGW",
      "time": "2017-03-10T15:01:19.645000",
      "type": "NATGW",
      "version": 11
    }
  ]
}

问题处理:

查看bootstrap-table documentation可以发现有这样一个处理方法:

Name Attribute Type Default Description
responseHandler data-response-handler Function function(res) {return res;} Before load remote data, handler the response data format, the parameters object contains: res: the response data.
  • 定制responseHandler方法:
// table init 配置项:
responseHandler: tableInit.responseHandler,
// 具体实现:
  tableInit.responseHandler = function (res) {
    console.log('onLoadSuccess, res is:', res);
    var response = {}
    response['total'] = res.meta.total_count
    response['rows'] = res.objects
    console.log('responseHandler, response is:', response);
  };

参考资料:

  • Django应用解决跨域API调用问题
  • https://q.cnblogs.com/q/85228/

你可能感兴趣的:(前台(AngularJS)后台(django)对接工作总结)