【问题标题】:The this.http.post() gives a 404 (Not Found) errorthis.http.post() 给出 404 (Not Found) 错误
【发布时间】:2021-12-18 12:47:04
【问题描述】:

我目前正在尝试使用 Angular 的服务器创建一个创建函数(以进行报价)。 所以我在 html 文件中输入了一个表单。

<form [formGroup]="addquoteform" (submit)="createquote()">
    <p>
        <mat-form-field appearance="outline">
            <mat-label>quote</mat-label>
            <input matInput placeholder="Placeholder" formControlName="quote">
            <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
        </mat-form-field>
    </p>
    <p>
        <button mat-raised-button color="primary">Submit</button>
    </p>
</form>

然后我在.ts文件中做了这个函数。

createquote(){
    this.dbService.addquote(this.addquoteform.value)
    .subscribe(data => {
      console.log("new quote")
    }, err => {
      console.log(err);
    })
  }

然后我在 server/quote.ts 中做了报价

interface QuoteData {
    quote : string;
}

export interface quote extends  QuoteData{

}

然后在 services/dbService.ts 文件中我创建了 this.http.post()

addquote(quoteObj: any) {
        return this.http.post(this.baseUrl + 'quote', quoteObj);
    }

但最后一个不起作用。 我得到的只是错误: POST http://localhost:4200/quote 404 (Not Found) 我尝试更改链接,但似乎没有任何帮助。 知道是什么原因造成的吗?

【问题讨论】:

  • baseUrl 是否正确? 4200 通常是 Angular 应用程序端口,而不是 Web 服务端口。
  • 在某个端口('8080' 或 smt)上侦听神秘的 API(节点 + 可能是 express / typescript)=> 所以将您的数据发布到 localhost:8080(不要忘记 cors)或smt 而不是 ng 开发服务器端口(除非您为 API 设置代理)...
  • @LucaFarsetti 感谢您的回复,但我认为问题不在于 baseUrl,因为我尝试更改 baseUrl 很多但没有任何改变。

标签: angular database typescript server crud


【解决方案1】:

原因可能是第一个:后端的端点不匹配。 第二:后端可能对配置中的所有API都有API前缀,你再检查一下。那是http://localhost:4200/api/qoute

【讨论】:

  • 感谢您的回复,但仍然出现同样的错误:POST http://localhost:4200/api/quote 404 (Not Found)
  • 你能把负责在后端存储报价的代码贴出来吗?还是服务器端?
  • 不就是services/dbService.ts文件吗?
  • 不,dbService.ts 文件正在对特定 URL 进行 API 调用,即 this.baseUrl + 'quote',它变成 localhost:4200/qoute。现在这个 API 必须在某个地方实现,才能执行 addQoute 任务。
  • 你的意思是我放this.app.post('/api/quote', this.quotePost.bind(this));的server/server.ts文件吗?
【解决方案2】:

您是否尝试调用任何后端 api?因为它不会尝试使用端口 4200 在您的前端应用程序上调用 thay api。显然不会存在。它只能为资产数据调用前端。如果要调用后端,请确保后端也在运行或服务器正在运行。因为查看上面的信息,它无法路由到您的服务器。

【讨论】:

    猜你喜欢
    • 2013-03-10
    • 2015-08-31
    • 2016-08-30
    • 2012-03-09
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    相关资源
    最近更新 更多