POST 上的查询参数
QueryParameter on POST
我正在使用 Angular2/4 构建网络应用程序。
我需要使用查询参数将对象发送给其余 api。
我的端点将只通过 url 接受对象,如下所示:
localhost:8080/api/node?type=bills&quantity=2
我的服务目前是这样的:
addInstance(instance: Instance) {
const params = {
type: instance.type,
quantity: instance.quantity
};
return this.http.post(this.baseUrl, params, {headers: this.headers})
.map(res => {
return res.json();
});
}
但它不起作用,并且在控制台日志中显示 url 中没有传递任何对象。我如何提供对 API 的正确调用?
您目前正在发送正文参数,而不是 url 个参数,并且您的端点需要 url 个参数。但是,您可以使用 URLSearchParams
在 angular 中构造 url 参数
尝试:
addInstance(instance: Instance) {
const params = new URLSearchParams();
params.set('type', instance.type);
params.set('quantity', instance.quantity);
return this.http.post(this.baseUrl, body?, {params: params} )
.map(res => {
return res.json();
});
}
您也可以直接使用字符串连接构造 url。
虽然,由于这是一个 post 请求,您应该使用 api 端点确定请求的主体应该是什么,因为通常 post 请求包含一个。否则,您应该更改 api 端点以使其成为获取请求。或者使 api 端点期望主体参数而不是 url 参数。
我正在使用 Angular2/4 构建网络应用程序。
我需要使用查询参数将对象发送给其余 api。 我的端点将只通过 url 接受对象,如下所示:
localhost:8080/api/node?type=bills&quantity=2
我的服务目前是这样的:
addInstance(instance: Instance) {
const params = {
type: instance.type,
quantity: instance.quantity
};
return this.http.post(this.baseUrl, params, {headers: this.headers})
.map(res => {
return res.json();
});
}
但它不起作用,并且在控制台日志中显示 url 中没有传递任何对象。我如何提供对 API 的正确调用?
您目前正在发送正文参数,而不是 url 个参数,并且您的端点需要 url 个参数。但是,您可以使用 URLSearchParams
在 angular 中构造 url 参数尝试:
addInstance(instance: Instance) {
const params = new URLSearchParams();
params.set('type', instance.type);
params.set('quantity', instance.quantity);
return this.http.post(this.baseUrl, body?, {params: params} )
.map(res => {
return res.json();
});
}
您也可以直接使用字符串连接构造 url。
虽然,由于这是一个 post 请求,您应该使用 api 端点确定请求的主体应该是什么,因为通常 post 请求包含一个。否则,您应该更改 api 端点以使其成为获取请求。或者使 api 端点期望主体参数而不是 url 参数。