我正在尝试从我的 Angular 应用程序进行 API 调用。我想要做的是使用命令参数向 API 发送发布请求。我已经做了很多服务器端测试以及通过传出请求,并且 $_POST
和 body
数据永远不会存在。因此,我很确定问题出在这段代码中。
public post(cmd: string, data: object): Observable<any> {
const params = new URLSearchParams();
params.set('cmd', cmd);
const options = new RequestOptions({
headers: this.getAuthorizedHeaders(),
responseType: ResponseContentType.Json,
params: params,
body: data,
withCredentials: false
});
console.log('Options: ' + JSON.stringify(options));
return this.http.post('http://t2w.dev/index.php', data, options)
.map(this.handleData)
.catch(this.handleError);
}
我尝试过许多不同的 JSON 结构作为数据
,但这是我要发送的核心内容:
{
"Username": "No thanks",
"Password": "Donno"
}
this.handleData
和 this.handleError
是一种将数据和错误作为参数的方法,并返回我想要的内容。
API 设置为记录来自 $_POST
的任何内容,这在从除我的 Angular 应用程序以外的任何地方运行请求时工作正常。到目前为止我做了什么:
- 传递原始查询而不是
URLSearchParams
。 - 传递没有正文的请求。
- 传递 RequestOptions 中的所有值。
- 将参数作为字符串传递。
- 将正文作为参数传递。
- 将主体作为
JSON.stringify({ "Username": "No thanks", "Password": "Donno"}
Console output of
RequestOptions
选项:{"method":null,"headers":{"Content-Type":["application/json"],"Accept":["application/json"],"X-CLIENT -ID":["380954038"],"X-CLIENT-SECRET":["5BgqRO9BMZ4iocAXYjjnCjnO7fHGN59WP8BTRZ5f"]},"body":"{}","url":null,"params":{"rawParams":"","queryEncoder":{},"paramsMap":{}},"withCredentials":false,"responseType":1} VM8529:1 XHR 完成加载:POST "http://t2w.dev/index.php".
有没有人知道为什么数据永远不会发送?
最佳答案
http.post的第二个参数是消息的主体,即有效负载而不是 url 搜索参数。在该参数中传递 data
。
post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response
public post(cmd: string, data: object): Observable<any> {
const params = new URLSearchParams();
params.set('cmd', cmd);
const options = new RequestOptions({
headers: this.getAuthorizedHeaders(),
responseType: ResponseContentType.Json,
params: params,
withCredentials: false
});
console.log('Options: ' + JSON.stringify(options));
return this.http.post(this.BASE_URL, data, options)
.map(this.handleData)
.catch(this.handleError);
}
编辑
您还应该检查第一个参数 (BASE_URL
)。它必须包含您要访问的完整 url(减去查询字符串)。我提到是因为你给它起的名字,我只能猜测当前的值是多少(也许只是域?)。
此外,也无需在 http 正文中发送的数据/负载上调用 JSON.stringify
。
如果您仍然无法到达终点,请在开发控制台中查看浏览器的网络事件以查看正在发送的内容。然后,您可以进一步确定是否使用正确的 header 和正文调用了正确的端点。如果它看起来是正确的,那么使用 POSTMAN 或 Fiddler 或类似的东西来查看你是否可以通过这种方式(在 Angular 之外)访问你的端点。
关于Angular 2 http post参数和正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44569409/