如何修复通过Angular App和NodeJS向Express服务器发送GET/POST请求时出现的404 Not Found问题

qybjjes1  于 2023-06-29  发布在  Node.js
关注(0)|答案(3)|浏览(143)

我正在尝试创建一个Angular应用程序,使用NodeJS将GET和POST请求发送到Express服务器。
当我为应用程序提供服务时,GET & POST请求应该发送到我的本地服务器,但我在控制台中收到一个错误,这个错误记录在下面。
另外,当我转到localhost:3000时,服务器正在运行。
下面是我的组件类:

import { Component, OnInit } from "@angular/core";
import { RootService } from "./root.service";

@Component({
  selector: "app-root",
  templateUrl: "./root.component.html",
  styleUrls: ["./root.component.css"]
})
export class RootComponent implements OnInit {
  constructor(private rootService: RootService) {}

  ngOnInit() {
    this.rootService.getAPIData().subscribe(
      response => {
        console.log("response from GET API is ", response);
      },
      error => {
        console.log("error is ", error);
      }
    );

    this.rootService.postAPIData().subscribe(
      response => {
        console.log("response from POST API is ", response);
      },
      error => {
        console.log("error during post is ", error);
      }
    );
  }
}

下面是root.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class RootService {

  constructor(private http: HttpClient) { }

  getAPIData(){
    return this.http.get('/api/getData')
  }

  postAPIData(){
return this.http.post('/api/postData', {'firstName' : 'Code', 'lastName' : 'Handbook'})
  }
}

下面是我的服务器代码:

const express = require('express')
const app = express()
const bodyParser = require('body-parser')

app.get('/', (req, res) => {
res.send('Welcome to Node API')
})

app.get('/getData', (req, res) => {
res.json({'message': 'Hello World'})
})

app.post('/postData', bodyParser.json(), (req, res) => {
res.json(req.body)
})

app.listen(3000, () => console.log('Example app listening on port 3000!'))

我还有这个proxy.conf.json文件:

{
  "/api/*": {
    "target": "http://localhost:3000",
    "pathRewrite": {"^/api" : ""}
  }
}

当我提供我的应用程序时,我将以下输出发送到控制台:
错误是
Object { headers:{...},状态:404,状态文本:“Not Found”,url:“http://localhost:4200/api/getData“,确定:名称:“HttpErrorResponse”,消息:“http://localhost:4200/api/getData的Http失败响应:404 Not Found”,错误:“\n\n\n\n错误\n\n\n

Cannot GET /api/getData

\n\n\n”} root.component.ts:18:8 post期间出现错误
Object { headers:{...},状态:404,状态文本:“Not Found”,url:“http://localhost:4200/api/postData“,确定:名称:“HttpErrorResponse”,消息:“http://localhost:4200/api/postData的Http失败响应:404 Not Found”,错误:“\n\n\n错误\n\n\n

Cannot POST /api/postData

\n\n\n”}
有人能帮我解决这个错误吗?

eeq64g8w

eeq64g8w1#

我认为你需要在启动Angular应用程序时传入proxy.conf的路径。
参考:https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

1rhkuytd

1rhkuytd2#

您的配置应该如下所示:

{
  "/api": {
    "target": "http://localhost:3000",
    "pathRewrite": {
      "^/api": ""
    }
  }
}
tzdcorbm

tzdcorbm3#

1.首先在根目录下创建一个文件“proxy.config.json”,并在里面添加以下行:

{
  "/api/*": {
    "target": "http://localhost:3000",
    "secure": false,
    "logLevel": "debug"
  }
}

**2.在“**angular.json”下脚本put:

"start": "ng serve --proxy-config proxy.config.json",

3.在终端写npm start

note: Don't write "ng serve" , it won't run proxy configuration file.

相关问题