【问题标题】:How to pass data from angular 6 to Nodejs?如何将数据从角度 6 传递到 Nodejs?
【发布时间】:2019-06-24 13:26:16
【问题描述】:

我正在使用 Angular 6,而我以前从未使用过 Angular。我需要将数据发送到 nodejs 服务器。我在角度函数中使用以下代码

     import { Component, OnInit } from '@angular/core';
     import { HttpClient,HttpHeaders  } from '@angular/common/http';

      const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json' })
       };


     fun_add(Id, cat) {
     return this.http.post('/go', data, 
      httpOptions).subscribe(result => {
        console.log(result);
       }, error => console.log('There was an error: '));
      }

在我的 nodejs 中,

    app.post('/go', function (req, res) {
      console.log("hi");
      })

但我无法访问服务器。我收到错误消息“出现错误”。 谁能帮我解决这个问题?

【问题讨论】:

  • http.post('http://localhost:port/go' 否则它不是有效的 URL
  • 应该是有效的,能给我们看看网络流量吗?
  • @trichetriche — 在我听说 WWW 之前就已经支持相对 URL。
  • @Quentin 这很酷,但 Angular 可能需要 HTTP url 而不是相对的。此外,使用/go 并不是真正的相对,它会尝试获取文件夹的根...不仅不是很清楚,而且非常随机
  • @trichetriche — Angular 及其调用的底层 XMLHttpRequest 对象在网页托管的 JavaScript 环境中运行。相对 URL 是相对于该页面的 URL。

标签: html node.js angular angular6


【解决方案1】:

您永远不会发送响应(例如使用res.send()),因此服务器会收到请求并坐在那里。

同时,客户端等待,等待,最终超时并抛出错误,因为服务器从未响应。

【讨论】:

  • 如果是这样的话他会看到console.log("hi");的结果
  • @trichetriche — 他们只报告了他们在浏览器中看到的内容。
  • @trichetriche — 关于 Node.js 在控制台上的输出,没有任何声明。这是事实,不是假设。
  • 我的错,there was an error 是捕获的错误。删除我之前的评论!
  • @quentin 我也尝试过发送响应。还是不行。
【解决方案2】:
    let api_url = 'http:localhost:portNumber'

   fun_add(Id, cat) {
      return this.http.post(api_url+'/go', data, 
          httpOptions).subscribe(result => {
            console.log(result);
       }, error => console.log('There was an error: '));
    }

【讨论】:

  • 你能打API吗? @BhavaniSankar 尝试以 res.status(200) 的形式发回响应; res.json({ 成功: "数据" });
  • 仍然没有。有没有其他方法可以将数据从 angular 发送到 nodejs?维沙尔哈斯纳尼
【解决方案3】:

在组件中添加这段代码

constructor(private http: HttpClient);

它正在工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-14
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 2017-08-04
    • 2018-07-08
    相关资源
    最近更新 更多