1. 什么是前后端分离开发的概念:

前端页面运行前端服务器上,负责页面的渲染(静态文件的加载)与跳转

后端代码运行在后端服务器上, 负责数据的处理(提供数据请求的接口)

2. 前后端分离开发碰到的问题 那就是跨域请求的问题:

什么是跨域问题: 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>
前端-下载方式体验

 

posted on 2019-04-26 14:32  kaikai2xiaoqi  阅读(332)  评论(0编辑  收藏  举报