Angular5 HttpClient send data but server can not understand its params

感情迁移 提交于 2019-12-24 21:25:32

问题


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

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'
    };

But server ( Laravel ) could not understand request parameters. Please let me know what is wrong with it?


回答1:


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");


来源:https://stackoverflow.com/questions/48986774/angular5-httpclient-send-data-but-server-can-not-understand-its-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!