typescript 我如何修复这个错误与我的API(404 not found)

2nc8po8w  于 11个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(138)

我正在制作一个应用程序,它从mongoDB中获取代码并将它们列出到网页上,但目前我在控制台中收到一个错误:
GET http://localhost:4200/api/code/codes/404(Not Found)zone.js:2863
我以前没有遇到过这个错误&我不确定是我的代码中有错误还是端口有问题,我的服务器在端口3000上启动,Angular 部分在端口4200上启动。

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/');
  }

}


而我的家庭组件是我试图显示代码的地方,

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 {}
}

x4shl7ld

x4shl7ld1#

当您像以前那样调用API时,您将向Web应用程序的同一个源发出请求,因此当您调用此路由时,不是调用您的API路由,而是调用您自己的Web应用程序的路由。
要解决这个问题,您需要检查API正在运行的端口,并执行以下操作之一:
1.创建一个代理文件,将您的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

相关问题