1. //app.module.ts:
  2. import {NgModule} from '@angular/core';
  3. import {BrowserModule} from '@angular/platform-browser';
  4. //HttpClientModule
  5. import {HttpClientModule} from '@angular/common/http';
  6. @NgModule({
  7. imports: [
  8. BrowserModule,
  9. //加入HttpClientModule
  10. HttpClientModule,
  11. ],
  12. })
  13. export class MyAppModule {}
  1. import { HttpClient, HttpHeaders } from '@angular/common/http';
  2. //发起一个 get 请求
  3. @Component(...)
  4. export class MyComponent implements OnInit {
  5. results: string[];
  6. //在构造函数中注入HttpClient
  7. constructor(private http: HttpClient) {}
  8. ngOnInit(): void {
  9. // 发送get请求
  10. this.http.get('/api/homead').subscribe(data => {
  11. console.log(data)
  12. },
  13. //请求错误
  14. err => {
  15. console.log('Something went wrong!');
  16. });
  17. }
  18. }

代理设置

  1. //在项目根目录下创建 proxy.conf.json
  2. {
  3. "/api": {
  4. "target": "http://localhost:3001/",
  5. "changeOrigin": true,
  6. "logLevel": "debug"
  7. }
  8. }

修改package.json

  1. "start": "ng serve --proxy-config proxy.conf.json",