本文介绍了Angular5 HttpClient发送数据,但服务器无法理解其参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提交常规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

然后,我编写了以下方法,以通过angular5 HttpClient向服务器发送发布请求:

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发送数据,但服务器无法理解其参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 01:49