angular2,将表单发布到后端restful错误:JSON输入意外结束

angular2,将表单发布到后端restful错误:JSON输入意外结束,angular,Angular,我得到了这个错误: accounts.service.ts?29fe:45语法错误:JSON输入意外结束。 就像服务器不喜欢json格式一样 当我使用Postman发送x-www-form_时,两个字段:lastname和firstname工作正常 我不太明白为了正确使用后端必须进行的转换,有一个后端使用x-www-form_urlencoded,另一个使用完整的json?因为大多数教程不使用任何形式的转换来从表单发送post数据。 我见过一些使用新URLSearchParams()的解决方案;

我得到了这个错误:

accounts.service.ts?29fe:45语法错误:JSON输入意外结束。 就像服务器不喜欢json格式一样

当我使用Postman发送x-www-form_时,两个字段:lastname和firstname工作正常

我不太明白为了正确使用后端必须进行的转换,有一个后端使用x-www-form_urlencoded,另一个使用完整的json?因为大多数教程不使用任何形式的转换来从表单发送post数据。 我见过一些使用新URLSearchParams()的解决方案;但是angular2中没有自动进行转换吗

从我的服务器日志中,当我与邮递员一起发送邮件时,我得到:

add: {"lastname":"mylast","firstname":"myfirst"}
但通过angular2组件,我得到:

add: {}
数据没有到达

我有这个部分:

import {Component, Input, OnInit} from '@angular/core';
import {AccountsService} from '../shared/index';


@Component({
    selector: 'app-accounts-form',
    templateUrl: 'accounts-form.component.html',
    styles: [require('./accounts-form.component.scss')],
    providers: [AccountsService]

})
export class AccountsFormComponent implements OnInit {
    @Input() accountId: string = '';
    public account: any =       {
        firstname: '',
        lastname: ''
    };

    constructor(private accountsService: AccountsService    ) {
    }

    ngOnInit() {

        if (this.accountId !='' ) {
            this.getById();
        }
    }

    onSubmit() {
        if (this.accountId =='' ) {
            console.log('submit new');
            this.accountsService
                .insert(this.account)
                .subscribe((data) => {
                        console.log(data);
                        this.account = data
                    },
                    error => console.log(this.account),
                    () => console.log('Insert complete'));

        } else {
            console.log('submit update '+this.accountId);
        }

    }


    private getById(): void {

        this.accountsService
            .getById(this.accountId)
            .subscribe((data) => {
                    console.log(data);
                    this.account = data
                },
                error => console.log(this.account),
                () => console.log('Get Item complete'));


    }

}
模板:

<form (ngSubmit)="onSubmit()">
<div class="form-group">
  <label for="lastname">Last Name</label>
  <input [(ngModel)]="account.lastname"  name="lastname"/>
</div>
<div class="form-group">
  <label for="firstname">First Name</label>
  <input [(ngModel)]="account.firstname"  name="firstname"/>
</div>
<div>
  <button type="submit" class="btn btn-default"
          >Submit</button>
</div>
</form>
我在我的服务上尝试过不使用表单值,而是使用带有&和json值的硬代码值,但不起作用:

  • 尝试使用发送数据&

    返回this.http.post(this.actionUrl,'firstname&=test1&lastname=test2',{headers:this.headers}) .map((响应:响应)=>响应) .接住(这个.把手错误)

  • 尝试使用json发送数据

    return this.http.post(this.actionUrl ,  {'firstname':'test1','lastname':'test2'},  { headers: this.headers })
        .map((response: Response) =>  response)
        .catch(this.handleError);
    
  • 这两种方法都不起作用

    更新:

    我已将insert()更改为我的服务:

    .map((response: Response) =>  response.json()) <-- removed .json() here;
    
    然后我得到了新的错误:

    core.umd.js?e2a5:2837 EXCEPTION: Error in ./AccountsFormComponent class AccountsFormComponent - inline template:3:9 caused by: Cannot read property 'lastname' of undefinedErrorHandler.handleError
    
    服务代码中实际更新的insert()函数:

    public insert(body: any): Observable<any> {
        console.log( 'insert url:'+ this.actionUrl  );
        console.log(JSON.stringify( body))
        return this.http.post(this.actionUrl ,  {'firstname':'test1','lastname':'test2'},  { headers: this.headers })
            .map((response: Response) => console.log(response))
            .catch(this.handleError);
    }
    

    您正试图将您的正文发布为
    'application/json'


    所以不要
    JSON.stringify()


    所以不要
    JSON.stringify()
    你的身体。

    我试过不使用JSON.stringify(),但都一样。。必须在我的后端更改某些内容吗?请执行以下操作:
    .map((响应:响应)=>console.log(响应))
    并将输出添加到您的问题中您在控制台上看到了什么??core.umd.js?e2a5:2837异常:./AccountsFormComponent类AccountsFormComponent-内联模板中的错误:3:9原因:无法读取UndeinederRorHandler.handleError@core.umd.js的属性“lastname”?e2a5:2837next我不明白模板为什么可以生成发送http post时出错,还有一件事,如果我不做“.map((response:response)=>console.log(response)),就永远不会看到错误?它是如何工作的?我试过使用JSON.stringify()而不使用JSON,但都是一样的。。必须在我的后端更改某些内容吗?请执行以下操作:
    .map((响应:响应)=>console.log(响应))
    并将输出添加到您的问题中您在控制台上看到了什么??core.umd.js?e2a5:2837异常:./AccountsFormComponent类AccountsFormComponent-内联模板中的错误:3:9原因:无法读取UndeinederRorHandler.handleError@core.umd.js的属性“lastname”?e2a5:2837next我不明白模板为什么可以生成发送http post时出错,还有一件事,如果我不做“.map((response:response)=>console.log(response)),就永远不会看到错误?它是如何工作的?
    .map((response: Response) => console.log(response))
    
    core.umd.js?e2a5:2837 EXCEPTION: Error in ./AccountsFormComponent class AccountsFormComponent - inline template:3:9 caused by: Cannot read property 'lastname' of undefinedErrorHandler.handleError
    
    public insert(body: any): Observable<any> {
        console.log( 'insert url:'+ this.actionUrl  );
        console.log(JSON.stringify( body))
        return this.http.post(this.actionUrl ,  {'firstname':'test1','lastname':'test2'},  { headers: this.headers })
            .map((response: Response) => console.log(response))
            .catch(this.handleError);
    }
    
    Request URL:http://localhost:3000/accounts
    Request Method:POST
    Status Code:200 OK
    Remote Address:[::1]:3000
    Response Headers
    view source
    Access-Control-Allow-Origin:*
    Connection:keep-alive
    Content-Length:0
    Date:Thu, 01 Dec 2016 14:21:04 GMT
    X-Powered-By:Express
    Request Headers
    view source
    Accept:application/json
    Accept-Encoding:gzip, deflate, br
    Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,fr;q=0.2
    Connection:keep-alive
    Content-Length:40
    Content-Type:application/json
    Host:localhost:3000
    Origin:http://localhost:8080
    Referer:http://localhost:8080/accounts-add
    User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36
    Request Payload
    view source
    {firstname: "test1", lastname: "test2"}
    firstname
    :
    "test1"
    lastname
    :
    "test2"