django 開發以前後端分離開發模式

1. 什麼是先後端分離開發的概念:前端

前端頁面運行前端服務器上,負責頁面的渲染(靜態文件的加載)與跳轉ajax

後端代碼運行在後端服務器上, 負責數據的處理(提供數據請求的接口)數據庫

2. 先後端分離開發碰到的問題 那就是跨域請求的問題:django

什麼是跨域問題: http協議不一樣, 端口不一樣, 服務器IP不一樣,這些都是跨域

3. 處理跨域的問題:後端

安裝django-cors-headers模塊
在settings.py中配置
# 註冊app
INSTALLED_APPS = [
    ...
    'corsheaders'
]
# 添加中間件
MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware'
]
# 容許跨域源
CORS_ORIGIN_ALLOW_ALL = True
在Django的settings文件作配置
$.ajax({
    url: 'http://127.0.0.1:8731/login/',
    type: 'post',
    data: {
        usr: 'abc',
        pwd: '123'
    },
    success: function (data) {
        console.log(data);
        // 能夠完成頁面的局部刷新
    }
})
def login(request):
    # 假設數據庫存放的用戶信息爲 abc:123
    if request.method == 'POST':
        usr = request.POST.get('usr', None)
        pwd = request.POST.get('pwd', None)
        if usr == 'abc' and pwd == '123':
            return JsonResponse({'status': 'OK', 'usr': usr})
    return JsonResponse({'status': 'error', 'usr': None})

文件的上傳與下載功能實現

<form>
    <input class="file" type="file">
    <button type="button" class="upload">上傳</button>
</form>
<script>
    $('.upload').click(function () {
        var form_data = new FormData();
        var file = $('.file')[0].files[0];
        form_data.append('file', file);
        $.ajax({
            url: '跨域上傳地址',
            type: 'post',
            data: form_data,
            contentType: false,  // 不設置內容類型
            processData: false,  // 不預處理數據
            success: function (data) {
                console.log(data)
            }
        })
    })
</script>
前端頁面--上傳功能
def upload(request):
    print(request.FILES)
    file_io = request.FILES.get('file', None)
    print(file_io)
    if file_io:
        with open(file_io.name, 'wb') as f:
            for line in file_io:
                f.write(line)

    return JsonResponse({'status': 'OK', 'msg': '上傳成功'})
後端之-上傳功能

 

from django.http import FileResponse
def download(request):
    file = open('123.md', 'rb')
    response = FileResponse(file)
    # 設置響應文件類型數據的響應頭
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="%s"' % file.name
    return response
後端-文件下載功能
<a href="http://127.0.0.1:8121/download/">下載</a>
<button type="button" class="download">下載</button>
<script>
    $('.download').click(function () {
        location.href = 'http://127.0.0.1:8121/download/'
    })
</script>
前端-下載方式體驗
相關文章
相關標籤/搜索