2017-05-06 190 views
0

我想從angular 2向node.js發送post請求。出於某種原因,在我提交表單後,我在瀏覽器的url欄中看到結果就像我一樣發送獲取請求。此外,它正在重新加載頁面。我沒有從角度和節點都得到任何控制檯錯誤。我檢查郵遞員和服務器工作正常。Angular 2 Http-Post不能正常工作

發送請求後url看起來像這樣;

http://localhost:3000/?username=testUser&email=test%test.com&password=34242

//server.js 
    app.post('/register', function(req, res){ 
    res.send('hello'); 
    console.log('success') 
    }) 

//http.service 
sendMyData(users : any) { 
    let bodyString = JSON.stringify(users); // Stringify payload 
    let headers  = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON 
    let options  = new RequestOptions({ headers: headers }); // Create a request option 
    return this.http.post('http://localhost:3000/register', bodyString, options) 
    .map((res : Response) => res.json()) 
} 

//header.component 
onSubmit(form : NgForm) { 
    this.httpService.sendMyData(form) 
     .subscribe(
     (data) => alert(data) 
    ) 
} 

//header.component.html 
<form (ngSubmit)='onSubmit(f)' #f='ngForm'> 
....... 
</form> 
+0

不相關,但將內容類型設置爲JSON並將對象/數組字符串化是由Angular默認完成的。你的代碼可以簡化爲'return this.http.post(url,users).map(...);'。 –

+0

您的網址缺少'註冊'嗎? – wannadream

+0

由於我發送它作爲一個post請求,我不認爲url需要改變。我只需要得到迴應,並在我的情況下console.log。 –

回答

0

我只是用this.httpService.sendMyData(form.value)我完全忘了,「形式」將返回所有類型屬性的整個對象解決了這個問題。所以它必須是form.value