好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

vue在body和query中如何向后端传参

在body和query中向后端传参

在vue向Django后端传参的时候,常常会出现request.body或者其他为空的现象,主要原因是参数存放的位置不对。这里总结一下两种传参方式。

data

我们需要传递的数据可以放在data中以键值对的形式来传递到后端。

export function registerM(username, password) {
? ? return request({
? ? ? ? url: 'login/register/',
? ? ? ? method: 'post',
? ? ? ? data: {
? ? ? ? ? ? nickname: username,
? ? ? ? ? ? pwd: password
? ? ? ? }
? ? })
}

在Django后端中我们通过request.data来访问vue传递的数据

? ? @action(methods=['post'], detail=False)
? ? @csrf_exempt
? ? def register(self, request, *args, **kwargs):
? ? ? ? username = request.data.get("nickname")
? ? ? ? pwd = request.data.get("pwd")

params

我们也可以通过params来传递数据,params也是健值对的形式。

export function SignInM(params) {
? ? return request({
? ? ? ? url: 'login/LogOn/',
? ? ? ? method: 'post',
? ? ? ? params: params
? ? })
}

在Django后端我们可以使用request.query_params.get()来获取vue前端传递的数据。

? ? @action(methods=['post'], detail=False)
? ? @csrf_exempt
? ? def register(self, request, *args, **kwargs):
? ? ? ? username = request.query_params.get('nickname')

vue往后台传参(不是传对象)

因为有规定必须用post提交

example

vue:

withdrawCount(){
? ? let formData = new FormData();
? ? formData.append("date",this.date);
? ? withdrawCount(formData).then(response => {
? ? });
},

js:

export function withdrawCount(query) {
? ? return fetch({
? ? ? ? url: commonUrl + '/withdrawCount',
? ? ? ? method: 'POST',
? ? ? ? data: query
? ? });
}

后台:

@PostMapping(value = "withdrawCount")
public Object withdrawCount(@RequestParam(required = true) int date) {
? ? return new UpmsResult(UpmsResultConstant.SUCCESS, dashboardService.withdrawCount(date));
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

查看更多关于vue在body和query中如何向后端传参的详细内容...

  阅读:56次