我收到此错误:
accounts.service.ts?29fe:45 SyntaxError:JSON输入的意外结束。 它就像服务器不喜欢json格式。
当我使用Postman发送x-www-form_urlencoded两个字段时:lastname和firstname运行良好。
我不太清楚我必须要做的转换才能与后端一起工作,后端有x-www-form_urlencoded而另一个有完整的json?因为大多数教程都没有使用任何类型的转换来从表单发送帖子数据。 我见过一些使用新的URLSearchParams()的解决方案;但是在angular2中没有自动进行转换?
当我使用Postman发送帖子时,从我的服务器日志中获取:
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>
服务:
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map'
import { Observable } from 'rxjs';
import { Configuration } from '../../app.constants';
@Injectable()
export class AccountsService {
private actionUrl: string;
private headers: Headers;
constructor(private http: Http, private configuration: Configuration) {
this.actionUrl = configuration.ServerWithApiUrl + 'accounts';
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json');
this.headers.append('Accept', 'application/json');
}
public insert(body: any): Observable<any> {
console.log( 'insert url:'+ this.actionUrl );
console.log(JSON.stringify( body))
return this.http.post(this.actionUrl , JSON.stringify( body), { headers: this.headers })
.map((response: Response) => response.json())
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
我的后端服务器有mongo和express4:
const insert = function (req, res) {
data = req.body;
console.log('add: ' + JSON.stringify(data));
objectDb.insertOne(data, function (err, result) {
if (err) {
res.send({'error': 'An error has occurred'});
} else {
res.send(result[0]);
}
});
};
我已尝试过我的服务,请不要使用表单值,而是使用&amp;;和json值,并且不起作用:
尝试使用&amp;
发送数据返回this.http.post(this.actionUrl,&#39; firstname&amp; = test1&amp; lastname = test2&#39;,{header:this.headers}) .map((响应:响应)=&gt;响应) .catch(this.handleError);
尝试使用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;
不再有错误:&#39; JSON输入的意外结束&#39;只是数据不会发送到服务器。
我已更新以获取回复日志:
.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
服务代码中实际更新的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);
}
on developper tool xhr tab我得到:
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"
答案 0 :(得分:2)
您正试图将自己的身体贴为'application/json'
..
所以不要JSON.stringify()
你的身体。