zoukankan      html  css  js  c++  java
  • angular 4 和django 1.11.1 前后端交互 总结

    首先 angular4 和django 1.11.1交互 有跨域问题 所以先关闭cors 和csrf验证

    一.解决跨域问题 cors

    github django-cors-headers

    1)安装corsheaders

    1
    pip install django-cors-headers

      

    2)配置 settings.py    

    D:Python27Libsite-packagesdjangoinappappsettings.py

    搜索 INSTALLED_APPS   添加  corsheaders

    'corsheaders',

    3)搜索   MIDDLEWARE  添加 (顺序不能乱)

    'corsheaders.middleware.CorsMiddleware',

    'django.middleware.common.CommonMiddleware',

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
       # 'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'corsheaders.middleware.CorsMiddleware',
     
    ]

    4)同时添加 MIDDLEWARE_CLASSES

    PS: #注释掉的是csrf 验证

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    MIDDLEWARE_CLASSES = [
        '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',
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    5)后续其它参数  

    CORS_ALLOW_CREDENTIALS = True

    CORS_ORIGIN_ALLOW_ALL = True

    允许跨域的域名列表 现在表示所有都可以
    CORS_ORIGIN_WHITELIST = (
    '*'
    )

    CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
    )

    CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
    )

    二.关闭csrf 验证

    找到settings.py 搜索 django.middleware.csrf.CsrfViewMiddleware 前面加# PyCharm快捷键  ctrl + /

    这样就关闭了所有的csrf验证

    参考路径: D:Python27Libsite-packagesdjangoinappappsettings.py

    前端方面

     组件内代码    D:wampangular4xxxsrcapp egister egister.component.ts

    1)导入HttpClient 和HttpErrorResponse

    1
    import {HttpClient, HttpErrorResponse} from '@angular/common/http'

    2)提供http 

    1
    constructor(private  http: HttpClient) { }

    3)完成模板提交函数onSubmit(value){}

    ①value就是模板里表单的值 regForm.vaue 

    ②然后进行json序列化 JSON.stringify(value)

    1
    const data =JSON.stringify(value); 

    ③发送给后端 django 这里就有跨域的问题 需要关闭django cors 和csrf 验证

    const data =JSON.stringify(value);         定义的json数据
    let url = 'http://127.0.0.1:8000/formgetdata';     发送的后台接口地址

    this.http.post(url,data,{

    responseType:'json'

    }).subscribe()

    ④接收后台传递的json

    只有JSON序列化的才能看到 JSON.stringify(data)

    取得json的值的话 就是data.username  

    也就是说先看到JSON.stringify(data) 有什么字段 才能用data.字段值获取到

    .subscribe(

    data => {

    console.log('请求成功!'+ data )

    let datalist = JSON.stringify(data);

    console.log(data.username)

    console.log(data.password)

    console.log(data.message)

    }

    )

     

      

    使用this.http.post(url,data,option) 发送post请求

    顶部导入

    import {HttpClient, HttpErrorResponse} from '@angular/common/http'

    constructor(private http: HttpClient) { }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    onsubmit(value){
       console.dir(value);
       console.dir(JSON.stringify(value));
     
       const data =JSON.stringify(value);
       this.http.post('http://127.0.0.1:8000/formgetdata',data,{
         responseType:'text'
       }).subscribe(
         data =>{
           console.log('请求成功!')
     
         },
         (err : HttpErrorResponse) => {
           if(err.error instanceof Error){
             // 前端报错
             console.log("前端报错-错误信息:",err.error.message)
           }
           else {
             //后端错误
             console.log(`后端报错-响应码: ${err.status}, body was: ${err.error}`);
           }
     
       }
     
       );
     
     }

    整体结构

     

     

    组件内模板写法 D:wampangular4xxxsrcapp egister egister.component.html

    1)输入input 双向绑定 [(ngModel)]="名字"  名字就是name属性值

    2)表单值 收集提交 form 绑定ngSubmit 

    ① 先定义表单名称 #regForm ="ngForm"

    ② 收集表单信息 regForm.value

    ③ 传递给组件 (ngSubmit)="onsubmit(regForm.value)" 组件内定义onsubmit函数

     

    后端 django

    准备工作 顶部导入

    import json

    from django.shortcuts import render

    from django.http import HttpResponse

    1.配置路由 urls.py     

    参考路径:D:Python27Libsite-packagesdjangoinappappurls.py 

    找到   urlpatterns  配置   url(r'^formgetdata',view.formgetdata)

    1
    2
    3
    4
    5
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^$',view.hello),
        url(r'^formgetdata',view.formgetdata)
    ]

    2.配置视图 view.py   

    D:Python27Libsite-packagesdjangoinappappview.py

    这里需要实现的就是两个功能

    1)接收angular4发送来的表单数据

    查看数据是否接收到: request.body

    接收表单数据:

    datalist = request.body.decode('utf-8')

    data = json.loads(datalist)

    username = data['username']

    password = data['password']

     参考资料

    https://stackoverflow.com/questions/29780060/trying-to-parse-request-body-from-post-in-django

    2) 返回json数据给前端

    res ={"username":username ,"password":password ,"message":"后台成功接收表单信息!后台请求成功"}

    return HttpResponse(json.dumps(res),content_type="application/json")

     上面两点完整代码截图

     

    实例代码参考

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    # -*- coding: utf-8 -*-
    #from django.http import  HttpResponse
    import json
    from django.shortcuts import render
    from django.http import HttpResponse
    import simplejson
     
     
     
     
    def hello(request):
        context = {}
        context['hello'] = 'Hello world! {{ hello }} 传值'
        return render(request,'hello.html',context)
     
    def formgetdata(request):
        if request.method == 'POST':
     
            print request.body
     
            dataunicode = request.body.decode('utf-8')
            data = json.loads(dataunicode)
            username =data['username']
            password =data['password']
            print data
            print username
     
     
            res={'username':username,"password":password,"message":"后台成功接收表单信息!后台请求成功"}
            return HttpResponse(json.dumps(res),content_type="application/json")
     
        else:
            return HttpResponse('请求失败')

      

     提示

     request.body 数据都在这里可以找到

    转载自:https://www.cnblogs.com/xxx91hx/p/7966787.html

  • 相关阅读:
    CTS2019 题解
    CTS2019 & APIO2019 游记
    WF 2019
    BZOJ 2560 及其加强
    UOJ 191
    SCOI2019 退役记
    HTML5 本地存储
    js数据类型
    解析json成javascript对象
    http状态码;
  • 原文地址:https://www.cnblogs.com/kaid/p/8011158.html
Copyright © 2011-2022 走看看