Angular 2 Http-Post不能正常工作
问题描述:
我想从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>
答
我只是用this.httpService.sendMyData(form.value)
我完全忘了,“形式”将返回所有类型属性的整个对象解决了这个问题。所以它必须是form.value
不相关,但将内容类型设置为JSON并将对象/数组字符串化是由Angular默认完成的。你的代码可以简化为'return this.http.post(url,users).map(...);'。 –
您的网址缺少'注册'吗? – wannadream
由于我发送它作为一个post请求,我不认为url需要改变。我只需要得到回应,并在我的情况下console.log。 –