//app.module.ts:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
//HttpClientModule
import {HttpClientModule} from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
//加入HttpClientModule
HttpClientModule,
],
})
export class MyAppModule {}
import { HttpClient, HttpHeaders } from '@angular/common/http';
//发起一个 get 请求
@Component(...)
export class MyComponent implements OnInit {
results: string[];
//在构造函数中注入HttpClient
constructor(private http: HttpClient) {}
ngOnInit(): void {
// 发送get请求
this.http.get('/api/homead').subscribe(data => {
console.log(data)
},
//请求错误
err => {
console.log('Something went wrong!');
});
}
}
代理设置
//在项目根目录下创建 proxy.conf.json
{
"/api": {
"target": "http://localhost:3001/",
"changeOrigin": true,
"logLevel": "debug"
}
}
修改package.json
"start": "ng serve --proxy-config proxy.conf.json",