【问题标题】:How can I fix this error with my API (404 not found)如何使用我的 API 修复此错误(未找到 404)
【发布时间】:2022-01-05 09:34:31
【问题描述】:

我正在制作一个应用程序,它从 mongoDB 获取代码并将它们列出到网页上,但目前我在控制台中遇到错误:

GET http://localhost:4200/api/code/codes/ 404(未找到)zone.js:2863

我之前没有遇到过这个错误,我不确定我的代码是否有错误或端口有问题,我的服务器在端口 3000 上启动,角度部分在端口 4200 上启动。这是我的api查找所有代码

router.get("/codes", async (req, res) => {
  try {
    Code.find({}, function (err, codes) {
      if (err) {
        console.log(err);
        res.status(501).send({
          message: `MongoDB Exception: ${err}`,
        });
      } else {
        console.log(codes);
        res.json(codes);
      }
    });
  } catch (e) {
    console.log(e);
    res.status(500).send({
      message: `Server Exception: ${e.message}`,
    });
  }
});

我的服务文件

export class CodeService {
  constructor(private http: HttpClient) {}

  findAllCodes() {
    return this.http.get('api/code/codes/');
  }

}

以及我试图显示代码的主组件 ts

export class HomeComponent implements OnInit {
  code: Code[];

  constructor(private codeService: CodeService) {
    this.codeService.findAllCodes().subscribe(
      (res) => {
        // Logging for debugging purposes
        console.log('--Server respons from findAllCodes--');
        console.log(res);
      },
      (err) => {
        console.log('--Server error--');
        console.log(err);
      },
      () => {

        console.log('--codes--');
        console.log(this.code);
      }
    );
  }

  ngOnInit(): void {}
}

【问题讨论】:

  • 我不确定我是否理解。如果是前端请求(前端在 4200 上运行)到后端(后端在 3000 上运行),那么您需要在请求中包含端口。也不清楚路由是否嵌套,例如,您将其显示为 GET 映射到 /codes,但向 /code/codes 发出请求。
  • 404 表示未找到您请求的路径。请参阅en.wikipedia.org/wiki/HTTP_404 - 所以/api/code/codes(如错误消息中所示)不是有效路径。

标签: node.js angular typescript rest


【解决方案1】:

当您调用 API 时,您将向 Web 应用程序的同一源发出请求,因此当您调用此路由时,不是调用您的 API 路由,而是调用您自己的 Web 应用程序的路由.

要解决此问题,您需要检查您的 API 在哪个端口中运行并执行以下操作之一:

  1. 创建一个proxy file,它将您的 API 调用重定向到您正在使用的端口。示例:

在您的根目录中:proxy.json

{
  "/api": {
    "target": "http://localhost:9000",
    "secure": false
  }
}
  1. 使用 API 的完整路径进行调用:
return this.http.get('http://localhost:[SERVER_PORT]/api/code/codes/');

如果您的服务器上没有 CORS 配置,则可能需要对其进行配置,因为您将从不同的域调用您的 API。如果您正在使用 node.js 和 express,请检查此link

【讨论】:

    猜你喜欢
    • 2018-07-21
    • 1970-01-01
    • 2020-07-10
    • 2022-10-09
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多