一、Django端
1.导入Mysql数据库需要在主程序下的_init_.py
import pymysql
pymysql.install_as_MySQLdb()
2.配置主程序下的urls.py
from django.contrib import admin
from django.urls import path,include
from Person import urls as p_urls
urlpatterns = [
path('admin/', admin.site.urls),
path('Person/',include(p_urls))
]
3.配置新建APP下的urls.py
from django.urls import path
from . import views
from Person.views import lei, AppRep1
urlpatterns = [
path('AppRep1/',AppRep1.as_view(),name='AppRep1')
]
4.新建App下的views.py
from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from rest_framework.views import APIView
from . import models
from .models import A
class AppRep1(APIView):
def get(self,request):
re = models.A.objects.filter(Name='white')
arg = []
for i in re:
content = {'姓名':i.Name,'年龄':i.Age}
arg.append(content)
print(arg)
print(type(arg))
ID = request.data.get('id')
# username = request.data.get('Name')
# password = request.data.get('password')
print(ID)
# print(username)
# print(password)
return HttpResponse(arg)
5.新建APP下的models.py
from django.db import models
# Create your models here.
class A(models.Model):
Name=models.CharField(max_length=12)
Age=models.IntegerField(max_length=12)
二、前端代码
1.js文件
import fetch from '@system.fetch';
import qs from 'querystring';
export default {
data: {
winfo:"",
},
onClick() {
fetch.fetch({
url:'http://127.0.0.1:8000/Person/AppRep1/',
data:qs.stringify({'id':1}),
responseType:"json",
method:"GET",
success:(resp)=>
{
this.winfo = resp.data;
console.log("返回的数据"+this.winfo)
},
fail:(resp)=>
{
this.winfo=resp.data;
console.log("获取数据失败"+this.winfo)
}
});
}
}
2.hml文件
<div class="container">
<div class="title">
<text>welcome</text>
</div>
<div>
<button onclick="onClick">请求响应</button>
</div>
<div>
<text>{{winfo}}</text>
</div>
</div>
三、配置文件
在Config.json中
1.
"deviceConfig": {
"default": {
"process": "com.huawei.hiworld.example",
"supportBackup": false,
"network": {
"cleartextTraffic": true
}
}
},
2.
"module": {
"reqPermissions": [
{
"name": "ohos.permission.GET_NETWORK_INFO"
},
{
"name": "ohos.permission.SET_NETWORK_INFO"
},
{
"name": "ohos.permission.INTERNET"
}
],
.....
}
在控制台输入npm install qs 和 npm install querystring
qs.stringify把一个参数对象格式化为一个字符串,将对象 序列化成 URL 的形式(a=b&c=d),以&进行拼接
JSON.parse() 方法用来解析JSON字符串,将JSON字符串转换为JSON对象(把key=value连接字符串转成对象,如:name=hehe&ange=10==>{name:'hehe', ange:10}
四、遇到的问题
1.遇到报错:no internet(版本过低,建议使用3.8版本以上)
2.Method Not Allowed(用的是POST,但是获取应用GET)
3.新版本安装js sdk报错(29条消息) DevEco Studio JS sdk下载问题_weixin_40183198的博客-CSDN博客