【问题标题】:java rest call get url net::ERR_FAILEDjava rest 调用获取 url net::ERR_FAILED
【发布时间】:2020-05-26 21:50:47
【问题描述】:

我正在写一个如下的休息电话

authenticationService(username: string, password: string) {
    debugger;
    let params = new HttpParams();
    params = params.append('username', username);
    params = params.append('password', password);
    return this.http.get(`http://localhost:8080/api/v1/basicauth?`,{params},
      ).pipe(map((res) => {
        this.username = username;
        this.password = password;
      }));
  }

从春季启动结束,我正在使用@RequestParams,如下所示

@GetMapping(path = "/basicauth")
    public AuthenticationBean helloWorldBean(@RequestParam(name = "username") String username,@RequestParam(name = "password") String password) {
        String status = authenticationService.isUserAuthenticated(username, password);
             return new AuthenticationBean("You are not authenticated");
    }

我收到类似

的错误

![this ]1

请帮我解决这个问题。谢谢:)

【问题讨论】:

  • 我不认为这个问题与 CORS 有关。
  • @Codelover,尝试将@CrossOrigin(origins = "host://url_of_your_frontend_server:port") 添加到您的控制器。
  • @NikitaLebed @CrossOrigin(origins="localhost:4200") 我已经添加了。
  • @Codelover 也发布您的跨源配置文件,并从您的 cmets 发布您缺少的协议 (http)

标签: java angular spring typescript spring-boot


【解决方案1】:

您可以使用 Angular 开发服务器提供的内置代理选项。更多信息请参考official documentation

在 src 文件夹中创建 proxy.config.json 并添加以下内容:

src/proxy.config.json

{
    "/api": {
        "target": "http://localhost:8080",
        "secure": false,
        "changeOrigin": true
    }
}

然后在 AuthenticationService 文件中,修改您的 HTTP 调用如下:

this.http.get<any>('/api/v1/basicauth', { params }).subscribe();

现在使用以下标志运行您的 Angular 应用程序:

ng serve --proxy-config src/proxy.config.json

替代方法

angular.json

...
"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.config.json"
    },
...

现在您可以像往常一样使用不带 --proxy-config 标志的 ng serve 命令。

注意

  1. 现在您可以调用 localhost:8080 服务器公开的任何端点,而无需如上所示的主机名,它会起作用。但请注意,这仅适用于开发设置/工作流程。

  2. 在像生产这样的高级环境中,您必须从与后端服务器相同的域托管 Angular 应用程序以避免 CORS 错误。但请注意,这不是克服 CORS 错误的唯一可用选项。

  3. 从您的代码 sn-p 中可以看出,您不需要添加“?”在 URL 的末尾,因为如果您设置了 params 对象,它将由 HttpClient 自动生成。

希望这会有所帮助...干杯,编码愉快!!!

【讨论】:

  • 为什么我们需要使用ng serve --proxy-config src/proxy.config.json 我们只能用ng-servle 编译吗
  • @Codelover --proxy-config 标志通知 Angular cli 包含代理设置。有两种方法可以通知 CLI 有关代理设置的信息。一种方法是在运行 ng serve 命令时使用标志指定它,或者您可以在 angular.json 文件中指定它们。我已经编辑了我的答案以包含替代方法。
猜你喜欢
  • 2020-06-23
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
相关资源
最近更新 更多