问题描述
当我提交一个普通的 HTML 表单时,我的后端服务(用 Laravel 编写)可以理解 POST 参数.
When I submit a regular HTML form, My back-end service ( written in Laravel ) can understand POST parameters.
我检查了浏览器中的请求标头.请求参数为:
I checked the request header in the browser. Request parameters are:
Form Data:
_token:v4xCN9fHMpZhoQMGHfbqI01XDsQ1nCxYhy3RDrw5
username:root
password:123456
然后我写了如下方法通过angular5HttpClient
向服务器发送post请求:
Then I wrote the following method to send a post request to the server via angular5 HttpClient
:
public post(url: string, data: any): Observable<any[]> {
const headers = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
});
return this.http.post( url, data,
{
headers: headers
}
).pipe(
tap(success => this.handleSuccess(success)),
catchError(this.handleError())
);
}
但是浏览器显示了一个不同的表单数据,如下所示:
But browser displays a different Form Data like this:
Form Data:
{"username":"asdf","password":"asdf","_token":"mytoken"}:
我将以下对象作为数据传递:
I passed the following object as data:
data = {
username: 'asdf',
password: 'asdf',
_token: 'mytoken'
};
但是服务器(Laravel)无法理解请求参数.请让我知道它有什么问题?
But server ( Laravel ) could not understand request parameters. Please let me know what is wrong with it?
推荐答案
你的 data
应该是一个 FormData
实例而不是一个普通对象(它将被 json 编码).示例:
Your data
should be a FormData
instance instead of a plain object (which will be json-encoded). Example:
const data = new FormData();
data.append("username", "asdf");
data.append("password", "asdf");
data.append("_token", "mytoken");
这篇关于Angular5 HttpClient 发送数据但服务器无法理解其参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!