如何发送一个对象到http.post请求?
问题描述:
我contact
包含object.I要发送到http.post method.Below是我的代码,我应该在哪里把contact
对象作为parameter.Please给出链接,如果任何也涉及到http.post API。 代码:如何发送一个对象到http.post请求?
createContacts(contact) {
console.log('the contact inside subscribe function',contact);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost:8080/contacts',{headers : headers}).subscribe(res => {
console.log('inside postmehtod of sub.function', res.json());//only objects
});
}
package.json
{
"name": "contactlist",
"version": "0.1.0",
"description": "A sample Node.js app using Express 4",
"engines": {
"node": "5.9.1"
},
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"devDependencies": {
"mongoose": "^4.6.2",
"body-parser": "^1.15.2",
"cors": "^2.8.0",
"del": "2.2.0",
"express": "^4.14.0",
"http": "0.0.0",
"method-override": "^2.3.6",
"morgan": "^1.7.0",
"superlogin": "^0.6.1"
}
}
答
打字稿交API:post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response>
实施例:
createContacts(contact) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost:8080/contacts', contact, {headers : headers})
.subscribe(res => {
console.log('inside postmehtod of sub.function', res.json());//only objects
})
}
我得到了所需的结果。你可以解释为什么这不起作用。 'this.http.post(的 'http://本地主机:8080 /联系人',JSON.stringify(接触),...)' 这里我已经加入'json.stringify'为什么代码不与工作这条线? – Aditya
你能描述*代码不工作吗?它应该工作。我不能重现这一点,虽然我不使用离子。不管我在后端和/或JSON.stringify在前端使用这里bodyParser,我总是从POST方法相同的数据在我的Node.js后端 – Tom
奇怪。你使用了哪个后端?你使用哪种角度版本?请做一个混帐'克隆https://github.com/jsdevtom/so_example.git && NPM我&& NPM运行debug',然后打开控制台看起来应该像'铬devtools铬链接:// devtools/?捆绑/ inspector.html实验=真v8only =真WS = 127.0.0.1:9229/9b6c1f94-DDAB-45f2-a551-0d9ee78c0f98' – Tom