How to transfer Javascript Object data when using Vue axios?

Abstract

We have introduced how to set global parameters for Vue axios and how to execute a network request, this post will introduce: How to use Vue axios to carry Javascirpt Object data?

Keywords: Vue , axios , Javascript Object  data, URLSearchParams , Python flask.

Vue axios carry data

When using Vue axios to execute a network request, you need to import and instantiate NetWorkService.js. If you need to carry data, you need to put the data into the URLSearchParams(). And if you want to carry a Javascript Object data, you also need to use JSON.stringify() method to format the object data as a string, otherwise the data received will get only a string [Object]”, not the real data.

				
					<template>
	<div>https://www.libertynlp.com Vue axios post example .vue</div>
</template>
<script>
	//mport NetWorkService.js
	import NetWorkService from 'NetWorkService.js';
	export default {
		name: '',
		components: {
		},
		data() {
			return {
			}
		},
		networkService: null,
		created() {
			//instantiate NetWorkService
			this.networkService = new NetWorkService();
		},
		mounted() {
		},
		methods: {
			async testAxiosPostWithData() {
				var url = '/test-post';
				
				//use URLSearchParams() to carry data
				var data = new URLSearchParams();
				data.append('name', 'test_post');
				//carry javascript object needing JSON.stringify()
				var test_object = [{
					"id": 1
				}, {
					"id": 2
				}];
				data.append("test_object", JSON.stringify(test_object));
			
				//execute network request
				var resp = await this.networkService.postService(url, data);
				console.log(resp);
			},
		},
	}
</script>
<style scoped lang="scss">
</style>

				
			

Python flask receive data

If you want to receive data formatted by JSON.stringify() carried in Vue axios request, the receiver needs to parse the received string to get the Javascipt Object data. Taking Python Flask as an example, you need to use json.loads() method to parse the received data.

				
					//python flask receiver
# -*- coding:utf-8 -*-
from flask import request,jsonify
import json
@app.route("/api/test-post", methods=['GET', 'POST'])
def testPost():
    resp = {'code': 200, 'state': 'get data success', 'data': {}}
    req = request.values
    name = json.loads(req['name'])
    #use json.loads() to parse data formated by JSON.stringify()
    test_object = json.loads(req['test_object'])
    return jsonify(resp)

				
			

Summarize

When using Vue axios to transmit data, you need to use URLSearchParams() , if you need to transmit Javascript Object data, you also need to use JSON.stringify() when executing the network request, and the receiver needs to use json.loads() to parse the string to restore the Javascript Object data.

Related articles

Coming soon

If yuo have any question or need any help 

you can leave a comment or connect me with weichaoxu1998@gmail.com

Edit Template

2 Comments