1

对我的 NestJS 应用程序进行 API 调用时,我收到以下错误。

core.js:6185 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: " https://localhost:3333/api/product-index ", ok: false, ...}

GET https://localhost:3333/api/product-index net::ERR_SSL_PROTOCOL_ERROR

从分别研究 Nest、Angular 和 NGXS 以及建议的处理方式,我已经正确设置了所有内容。我唯一能想到的就是修改参考,localhost:3333/api看看我是否定位到一个不存在的位置。我注意到当我更改为时https,我得到一个 CORS 错误,即使包含在文件http中也不会消失。我已经观看并阅读了一些将 NestJS 连接到 Angular 的教程,一旦他们设置了文件,它就可以工作了。我一直在查看 nrwl 网站上的教程,据我所知,我已经正确设置了所有内容。enableCors()main.ts

这是main.ts文件在我的 Nest 应用程序中的样子

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const globalPrefix = 'api';
  app.setGlobalPrefix(globalPrefix);
  const port = process.env.port || 3333;
  await app.listen(port, () => {
    console.log('Listening at http://localhost:' + port + '/' + globalPrefix);
  });
}

bootstrap();

serve文件中我的前端项目的数据angular.json如下所示

"serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
    "browserTarget": "cre8or-maker:build",
    "proxyConfig": "apps/cre8or-maker/proxy.conf.json"
}

我的前端项目中的proxy.conf.json文件看起来像这样

{
    "/api": {
      "target": "https://localhost:3333",
      "secure": false,
      "logLevel": "debug"
    }
}

我的 NGXS 模块中有一个服务文件,它product-index向 Nest App 中的控制器发出请求,如下所示

export class ProductIndexService{

    constructor(private httpClient: HttpClient){}

    private readonly URL: string = 'https://localhost:3333/api';




    public fetchProductIndexList():Observable<CattegoryIndexItem[]>{
        const path: string = this.URL + '/product-index';

        return this.httpClient.get(path) as Observable<CattegoryIndexItem[]>;
    }
}

我的environments/environments.ts档案

export const environment = {
  production: false,
  apiUrl: '/api'
};

我的environments/environments.prod.ts档案

export const environment = {
  production: true
};

正如我之前提到的,我尝试了诸如在路径中添加和删除以及在and/api之间来回切换之类的操作,但它不起作用。我可以成功调用控制器,因此我知道 Nest 中的所有内容都已正确设置,从错误中显示的路径来看,我似乎从我的 NGXS 状态正确定位它。这里有什么问题?我错过了什么,否则我应该看看?httphttpsproduct-indexlocalhost:3333

4

1 回答 1

3

在四处挖掘之后,我发现了一种在我们的应用程序中启用 cors 的替代方法,即将其应用于文件中的函数create(),如下所示NestFactorymain.ts

const app = await NestFactory.create(AppModule, {cors: true});

这使错误消失了。我不知道为什么这和app.enableCors(). 我正在使用 Angular 9.1,所以可能有一些东西在阻止 Nest 建立连接。

于 2020-04-02T04:25:16.750 回答