【问题标题】:Angular 2 Http-Post is not workingAngular 2 Http-Post 不工作
【发布时间】:2017-05-06 22:54:25
【问题描述】:

我正在尝试从 Angular 2 向 node.js 发送发布请求。出于某种原因,在我提交表单后,我会在浏览器的 url 栏中看到结果,就像我发送 get 请求一样。此外,它正在重新加载页面。我没有从角度和节点中得到任何控制台错误。我用邮递员检查过,服务器工作正常。

请求发送后的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>

【问题讨论】:

  • 不相关,但是将内容类型设置为 JSON 并将对象/数组字符串化是由 Angular 默认完成的。您的代码可以简化为return this.http.post(url, users).map(...);
  • 您的网址是否缺少“注册”?
  • 由于我将其作为发布请求发送,我认为 url 根本不需要更改。在我的情况下,我只需要获得响应和 console.log。

标签: angular


【解决方案1】:

我刚刚使用this.httpService.sendMyData(form.value) 解决了这个问题,我完全忘记了“form”返回具有各种属性的整个对象。所以必须是form.value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 2016-07-09
    • 2017-12-07
    • 1970-01-01
    相关资源
    最近更新 更多