【问题标题】:Getting 404 error with Angular 4 http requestAngular 4 http请求出现404错误
【发布时间】:2018-05-27 17:29:49
【问题描述】:

我的 AngularJS4 项目中有以下代码:

const url = "http://localhost:4151/test";
     this.http.get(url).toPromise()
         .then((r) => {
             console.log("SUCCESS", r);
         })
         .catch((e) => {
             console.error("ERR", e);
         });

在浏览器栏中键入 URL 时可以正常工作,并且我在服务器端启用了 CORS 标头:

// Allow CORS
this.app.use(function(req: Request, res: Response, next: Function) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

每当我从 Angular 应用程序调用服务器时,它都会返回 404 - Not Found 错误。

任何想法如何解决这个问题?

谢谢。

【问题讨论】:

  • 在黑暗中刺伤。 (在我目前的工作中,我也沉浸在 prod CORS 调试中:P)。 [a] 确保您的服务器(实际上)设置为允许来自您的客户端运行位置的请求,或全部。 [b] 你可以直接点击 API 端点吗? (例如,不是通过应用程序)(只是试图排除一些事情)
  • 嗯,如果您使用的是 Angular cli,请尝试设置 proxy.conf.json。 DOCS

标签: angular


【解决方案1】:
HttpClientInMemoryWebApiModule.forRoot(
  InMemoryDataService, { dataEncapsulation: false }
)

从您的 app.module.ts 文件中删除上述行。我猜你把它放在从文档中学习 httpclient 的项目部分中

【讨论】:

    【解决方案2】:

    对于遇到同样问题的人,我通过在我的后端 spring RESTful 方法中添加“@ResponseBody”来修复。

    【讨论】:

      【解决方案3】:

      如果有人在下面的问题之前发现了这个问题。

      这是问题所在: Angular4 giving 404 for json data that exists and is publicly serving

      我以本教程为基础,仍然使用HttpClientInMemoryWebApiModule 来拦截http 调用。我把它注释掉了,它工作正常。

      ...
      // This needed to be commented out vvv
      // import { HttpClientInMemoryWebApiModule } from "angular-in-memory-web-api";
      // import { InMemoryDataService } from "./services/dataSvc/in-memory-data.service";
      
      @NgModule({
          declarations: [
              AppComponent
          ],
          imports: [
              BrowserModule,
              FormsModule,
              MyRoutingModule,
              HttpClientModule,
      
              // The HttpClientInMemoryWebApiModule module intercepts HTTP requests
              // and returns simulated server responses.
              // Remove it when a real server is ready to receive requests.
              // This needed to be commented out vvv
              // HttpClientInMemoryWebApiModule.forRoot(
              //     InMemoryDataService, { dataEncapsulation: false }
              // )
          ],
          providers: [MessageService],
          bootstrap: [AppComponent]
      })
      export class AppModule { }
      

      【讨论】:

        猜你喜欢
        • 2014-11-20
        • 1970-01-01
        • 2013-02-15
        • 2013-08-25
        • 2017-06-05
        • 2017-06-23
        • 2020-09-16
        • 2012-12-12
        • 2018-04-17
        相关资源
        最近更新 更多