【问题标题】:Problem with http call in angular. Cant send it角度中的http调用问题。发不出去
【发布时间】:2020-02-06 13:06:10
【问题描述】:

大家好,我的应用程序中的角度调用确实存在很大问题。首先,我将在这里传递我的代码。

角度服务

path = 'http://localhost:3000';
  httpOptions = {
    headers: new HttpHeaders({'Content-Type': 'application/json'})
  };
  constructor(private http: HttpClient) { }
  getProducts(): Observable <any> {
    return this.http.get<any>(this.path + '/api/products');
  }

server.js 的一部分

client.connect(err => {
  collectionUsers = client.db("users").collection("users");
  hivesDatabase = client.db("hives");
  });
  app.listen(3000, () => {
    console.log('Server started at port 3000');
  });
app.use(bodyParser.json());
app.route('/api/products').get(async (req, res) => {
  let response = [];
  collectionUsers.find().toArray().then(items => {
    items.forEach(item => {
      response.push(item);
    });
    res.send(response);
  });
});

错误:error img link

我真的不知道这段代码有什么问题..请帮助我:(

【问题讨论】:

  • 请提供更多信息。服务器启动了吗?如何在同一个端口上运行 Angular 和服务器?或者如何连接到具有不同端口的服务器而不会出现 CORS 错误?我假设您在 Node.Js 上使用 Express.Js,而 Angular CLI 用于前端,对吗?

标签: node.js angular mongodb server angular-httpclient


【解决方案1】:

这个错误的原因是我使用Angular Tour of Heroes applcation作为我的基础,并且我没有删除依赖

"angular-in-memory-web-api": "~0.2.4",

就是这样……

【讨论】:

    【解决方案2】:

    这个问题可能有多种原因:

    我会采用以下方法:

    1. 如果您有真正的后端,请使用 Postman 检查您是否得到正确的响应。
    2. 始终尝试返回所需的对象类型(如果服务已知且需要),而不是“any”。
    3. 很可能是由于具有 InMemoryWebApiModule 依赖项。如果您在应用程序中伪造后端,则需要将其删除。

    【讨论】:

      猜你喜欢
      • 2016-09-17
      • 2019-11-16
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多