前端使用 vue2 版本 ,后端使用django
查看已安装的包
npm list --depth=0
├── @babel/core@7.18.10
├── @babel/eslint-parser@7.18.9
├── @vue/cli-plugin-babel@5.0.8
├── @vue/cli-plugin-eslint@5.0.8
├── @vue/cli-service@5.0.8
├── ant-design-vue@1.7.8
├── axios@0.27.2
├── core-js@3.24.1
├── echarts@4.9.0
├── eslint-plugin-vue@8.7.1
├── eslint@7.32.0
├── v-charts@1.19.0
├── vue-router@3.5.4
├── vue-template-compiler@2.7.8
└── vue@2.7.8
npm i axios
将服务器开在80端口
python manage.py runserver 80
Django version 3.2.5, using settings ‘mysite.settings’
Starting development server at http://127.0.0.1:80/
@csrf_exempt
导包
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
import simplejson
if request.method == "POST":
data = simplejson.loads(request.body)
return JsonResponse(data)
代理服务器配置
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
'/jango': {
target: 'http://localhost:80',
pathRewrite: { '^/jango': '' },
// ws: true, //用于支持websocket
// changeOrigin: true //用于控制请求头中的host值
},
// 支持向多个服务器发送请求
'/demo': {
target: 'http://localhost:5001',
pathRewrite: { '^/demo': '' },
// ws: true, //用于支持websocket
// changeOrigin: true //用于控制请求头中的host值
}
}
}
})
^/jango
: 只有 jango 开头的 url 链接,才经过代理服务器转发。
target: 'http://localhost:80'
, 写对方服务器的 ip 和 端口。
pathRewrite: { '^/jango': '' }
, 代理服务器在转发时,''
空字符替换jango
。
http://localhost:8080/jango/xxx
==>
http://localhost:80/xxx
export default {
data() {
return { };
},
methods: {
getXXX() {
axios.get("http://localhost:8080/jango/xxx").then(
(response) => {
console.log("请求成功了", response.data);
},
(error) => {
console.log("请求失败了", error.message);
}
);
},
}
}
【注意】
axios.get("http://localhost:8080/jango/xxx")
, 这里是向代理服务器请求,这里填写代理服务器的 ip
和端口。代理服务器的ip是localhost
,端口是vue所在的那个端口。
由于axios是异步的,为了使得axios在某个事件后执行,可使用计时器(延时参数也可以不填),将axios事件推到队尾。
axios.get("http://localhost:8080/api/query").then(
(response) => {
console.log("请求成功了", response.data);
console.log(this.info);
this.info = response.data;
setTimeout(() => {
this.$emit("back", 1, 1, this.$refs.ali.innerText)
});
},
(error) => {
console.log("请求失败了", error.message);
}
);
postData() {
axios({
url: "http://localhost:8080/jango/print/post",
method: "post",
//发送格式为json
data: JSON.stringify({ name: "jie", age: 18 }),
// data: { name: "jiejie", age: 18 },
}).then(
(response) => {
console.log("请求成功了", response.data);
},
(error) => {
console.log("请求失败了", error.message);
}
);
},
在浏览器的网络监视中发现,后端把前端发出去的参数返回来时是如下格式:
{"name":"jie","age":18}: ""
,但我们希望它返回的是 {"name":"jie","age":18}
。
注意这不是前端的问题,
后端正确的处理POST传参的方式
if request.method == "POST":
data = simplejson.loads(request.body)
return JsonResponse(data)
以下是错误的方式:
×
if request.method == "POST":
data = request.POST
return JsonResponse(data)