与前端和后端的错误沟通(Java – Angular)

我尝试使用Java / Spring Boot后端来交stream我的Angular Frontend。 但terminal显示我这个错误:

[HPM]尝试从localhost:4500代理请求/ api / dados时发生错误:http:/ localhost:8080(ECONNREFUSED)( https://nodejs.org/api/errors.html#errors_common_system_errors )

这是我的exemple.service.ts(Angular)代码。 在这里我请求数据:

import {Injectable} from "@angular/core"; import {Http, Response} from "@angular/http"; import 'rxjs/Rx'; @Injectable() export class ExService{ constructor(private http: Http){ } getName(){ return this.http.get("/api/dados").map( (response: Response) =>{ return response.json(); } ); } } 

这里是我的exemple.java(Java代码)。 它负责发送数据:

 package com.lucas.bef.Envia; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/dados") public class Dados { String teste; public Dados(){ this.teste = "LUCAS"; } public void setNome(String nome){ this.teste = nome; } @GetMapping( value = {"","/"}) public String getNome(){ return teste; } } 

如果我启动Spring应用程序…terminal显示一个消息Tomcat在8080端口启动。

我创build一个configuration代理文件(proxy-conf.json),像这样:

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

请有人帮助我。 我需要这样做。 非常重要。 谢谢!

问题似乎是在不同的端口上运行这两个应用程序(前端和后端)。 这样的请求被称为CORS 。 你可以像这样在Spring-Boot App中启用cors。 或者对于临时testing,请下载这个Chrome 插件

首先你已经设定了“目标”:“http:/ localhost:8080”,错了! 它是http:// localhost:8080

也请尝试重写这样的服务请求

  getName(){ return this.http.get("http://localhost:8080/api/dados").map( (response: Response) =>{ return response.json(); } ); } 

检查它是否工作! 您必须订阅服务方法中的Observable响应

你也必须允许你的弹簧服务器与angular度应用程序进行通信。 要做到这一点,你必须从后端configuration你的CORS

 import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.filter.GenericFilterBean; public class CORSFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (((HttpServletRequest) req).getMethod().equals("OPTIONS")) { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "http://localhost:4500"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE"); response.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, " + "X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"); } else { chain.doFilter(req, res); } } }