本文介绍了如何在Angular 2中发布JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不明白我在做什么错,当我尝试获取json时,服务器返回"undefined".
I don't understand what I am doing wrong, my server returns "undefined" when I try to get the json.
POST(url, data) {
var headers = new Headers(), authtoken = localStorage.getItem('authtoken');
headers.append("Content-Type", 'application/json');
if (authtoken) {
headers.append("Authorization", 'Token ' + authtoken)
}
headers.append("Accept", 'application/json');
var requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: this.apiURL + url,
headers: headers,
body: data
})
return this.http.request(new Request(requestoptions))
.map((res: Response) => {
if (res) {
return { status: res.status, json: res.json() }
}
});
}
还有我的功能
login(username, password) {
this.POST('login/', {test: 'test'}).subscribe(data => {
console.log(data)
})
}
当我尝试执行此操作时,请求正文如下所示:
When I try this, the request body looks like this:
因此,它没有发送实际的json,而是发送了"[object Object]".代替请求有效负载",它应该是"JSON".我在做什么错了?
So instead of sending actual json, it just sends "[object Object]".Instead of "Request payload" it should be "JSON". What am I doing wrong?
推荐答案
您需要对有效载荷进行分类
You need to stringify the payload
var requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: this.apiURL + url,
headers: headers,
body: JSON.stringify(data)
})
这篇关于如何在Angular 2中发布JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!