2

http的get请求中的url中添加Object参数

 2 years ago
source link: https://ioridy.github.io/2021/01/18/pass-object-parameters-with-url-in-http-get-request/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

http的get请求中的url中添加Object参数

2021-01-18

一直以来http的get请求中,都没有尝试带过复杂对象参数,最新在写grpc时, 使用了框架自动转化rpc请求到http请求,参数定义时没有注意复杂度,定义了个对象嵌套对象的请求参数,所以尝试了下载请求的url中携带对象参数的方案。

先说解决方案, 把对象序列化成字符串,encode然后加到url中即可。 请参考下面的sample:

http的get请求中的url中添加Object参数

  • server端定义的请求参数对象
type HelloRequest struct {
Id int32
Name string
User *User
}

type User struct {
Id int32
Name string
}

  • 前端发送请求
var helloRequest = {"id": 2,"name": "User",}

var helloRequestString = encodeURI(JSON.stringify(helloRequest))
var url = 'http://localhost:8080/v2/hello?id=1&name=hello&user=' + helloRequestString

var ajaxObj = new XMLHttpRequest();
ajaxObj.open('get', url);
ajaxObj.send();

只需要把第一层里面嵌套的对象序列化即可


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK