从Angular前端向Node.js后端发出HttpClient获取请求时发生错误

时间:2019-06-28 19:42:23

标签: node.js angular mongodb http

我收到错误:尝试从Angular的前端向Node.js的后端端点发出HttpClient获取请求时,无法GET /显示在本地主机URL上。我的后端端点正在显示来自MongoDB数据库的正确数据,但是在尝试将后端连接到前端时遇到了这些问题。

节点后端代码:

class Test {
    val array: Array<Int> = Array(3){0}
}

fun main(args: Array<String>) {
    val test = Test()

    for (i in 0..2) // Ok
        test.array[i] = i

    for (i in 0..3) // throws ArrayIndexOutOfBoundsException
        test.array[i] = i

    test.array = arrayOf(0, 1, 2, 3) // compile time error: Val cannot be reassigned
}

app.component.ts中的角度代码(改编自How to make post request from angular to node server):

app.get("/temp/route1", (req, res, next) => {
   myDatabaseCollection.find({ number: "10" }).then(pages => {
      res.status(200).json({
        items: pages
      });
    });
  });

谢谢,如果有人能够帮助我,那将是很棒的!

1 个答案:

答案 0 :(得分:0)

添加构造函数constructor(private http: HttpClient) { }

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})

export class AppComponent {
  title = 'my-tool';
  user = { id : 1, name : "Hello"};

constructor(private http: HttpClient) { }

  getData() {
    this.http.get('http://localhost:1025/temp/route1', JSON.stringify(this.user), {})
    .subscribe(
       (response: any) => {
          console.log(response);
        },
        (error: any) => {
         console.log(error);
        }
    );
  }
}