我一直在通过 ng serve 运行我的 Angular 应用程序进行开发,并且没有遇到任何错误。但是,在使用 SSR 时,每当我加载一个组件,该组件发出一个 http 请求作为其 ngOnInit 方法的一部分时,我的服务器日志中就会出现错误。我的策略有问题吗?
我没有通过谷歌搜索我的错误找到任何有用的信息。我应该在页面完全加载之前等待以提出我的请求,还是使用其他方法?如果是这样,我该怎么做?
我正在使用 http-proxy-middleware 包向 django 服务器发送请求。https://github.com/chimurai/http-proxy-middleware
这是作为 ngOnInit 的一部分发出请求时我得到的错误:
ERROR Error
at XMLHttpRequest.send (C:\{...}\dist\{...}\server\main.js:201490:19)
at Observable.rxjs__WEBPACK_IMPORTED_MODULE_1__.Observable [as _subscribe] (C:\{...}\dist\{...}\server\main.js:23724:17)
at Observable._trySubscribe (C:\{...}\dist\{...}\server\main.js:186583:25)
at Observable.subscribe (C:\{...}\dist\{...}\server\main.js:186569:22)
at scheduleTask (C:\{...}\dist\{...}\server\main.js:106745:32)
at Observable.rxjs__WEBPACK_IMPORTED_MODULE_7__.Observable [as _subscribe] (C:\{...}\dist\{...}\server\main.js:106807:13)
at Observable._trySubscribe (C:\{...}\dist\{...}\server\main.js:186583:25)
at Observable.subscribe (C:\{...}\dist\{...}\server\main.js:186569:22)
at subscribeToResult (C:\{...}\dist\{...}\server\main.js:196664:23)
at MergeMapSubscriber._innerSub (C:\{...}\dist\{...}\server\main.js:191854:116)
这是我的测试组件的相关部分:
export class TestComponent implements OnInit {
output: String = "The server is not running or is not connected"
constructor(private httpTestService: HttpTestService) { }
ngOnInit(): void {
this.testGetRequest();
}
testGetRequest() {
this.httpTestService.testGetRequest().subscribe(temp => {
this.output = temp.message; // response is json with a 'message' attribute
});
}
}
这是我的 HttpTestService 的相关部分:
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
testGetRequest(): Observable<any> {
return this.http.get('/api/endpoint1');
}
我相信我的 server.ts 的这一部分可能很重要:
import { createProxyMiddleware } from 'http-proxy-middleware';
export function app() {
const server = express();
const distFolder = join(process.cwd(), 'dist/.../browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
server.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));
server.set('view engine', 'html');
server.set('views', distFolder);
// re-route requests to /api/ to the django REST api
server.use('/api/**', createProxyMiddleware({ target: 'http://localhost:8000', changeOrigin: true }));
即使使用 SSR 运行,应用程序也能正常运行,除了我在服务器控制台中遇到的错误。