Meu sistema está fazendo uma requisição na porta 8000 aparti do localhost 4200 Quando uma requisição é feito por um protocolo um dominio em portas diferentes da origem, que é o meu caso a aplicação Angular está na porta 4200 a api java está na porta 8000 nesse caso por segurança os navegadores restringem o acesso, não permite que a requisição seja feita, o próprio navegador já tem essa camada de segurança que restringem o acesso.
mas existe um mecanismo conhecido como CORS que permite que os sevidores configure o controle de acesso cross domain, ou seja, com o protocolo, com dominio ou portas diferentes da origem, o back-end que estou usando já tem a implementação de cross domain, como podem ver abaixo;
package com.example.wladimir.money.cors;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
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.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.example.wladimir.money.config.property.AlgamoneyApiProperty;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
@Autowired
private AlgamoneyApiProperty algamoneyApiProperty;
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin", algamoneyApiProperty.getOriginPermitida());
response.setHeader("Access-Control-Allow-Credentials", "true");
if ("OPTIONS".equals(request.getMethod()) && algamoneyApiProperty.getOriginPermitida().equals(request.getHeader("Origin"))) {
response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept");
response.setHeader("Access-Control-Max-Age", "3600");
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, resp);
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
mas é preciso passar o parâmetro de inicialização dele qual é a origem permitida, porque por padrão nesse caso aqui por padrão ele está permitindo a origem :8000
esse é o parâmetro:
java -jar wladimir-api-1.0.0-SNAPSHOT.jar --spring.datasource.username=postgres --spring.datasource.password=1234 algamoney.origin-permitida=http://localhost:4200
Ao rodar a aplicação ele não gerar nenhuma mensagem de erro e consigo até listar meus registros pelo banco de dados como podem ver abaixo;
Qual é problema?
Veja a mensagem de erro no consoles do navegador chrome
2zone.js:2933 OPTIONS http://localhost:8000/lancamentos?resumo 401 ()
scheduleTask @ zone.js:2933
ZoneDelegate.scheduleTask @ zone.js:411
onScheduleTask @ zone.js:301
ZoneDelegate.scheduleTask @ zone.js:405
Zone.scheduleTask @ zone.js:236
Zone.scheduleMacroTask @ zone.js:259
(anonymous) @ zone.js:2966
proto.(anonymous function) @ zone.js:1366
(anonymous) @ http.js:1605
Observable._trySubscribe @ Observable.js:172
Observable.subscribe @ Observable.js:160
(anonymous) @ Observable.js:286
ZoneAwarePromise @ zone.js:890
Observable.toPromise @ Observable.js:284
LancamentoService.pesquisar @ lancamento.service.ts:18
LancamentosPesquisaComponent.pesquisar @ lancamentos-pesquisa.component.ts:20
LancamentosPesquisaComponent.ngOnInit @ lancamentos-pesquisa.component.ts:16
checkAndUpdateDirectiveInline @ core.js:12096
checkAndUpdateNodeInline @ core.js:13599
checkAndUpdateNode @ core.js:13542
debugCheckAndUpdateNode @ core.js:14414
debugCheckDirectivesFn @ core.js:14355
(anonymous) @ AppComponent.html:4
debugUpdateDirectives @ core.js:14340
checkAndUpdateView @ core.js:13509
callViewAction @ core.js:13859
execComponentViewsAction @ core.js:13791
checkAndUpdateView @ core.js:13515
callWithDebugContext @ core.js:14741
debugCheckAndUpdateView @ core.js:14278
ViewRef_.detectChanges @ core.js:11301
(anonymous) @ core.js:5787
ApplicationRef.tick @ core.js:5787
ApplicationRef._loadComponent @ core.js:5853
ApplicationRef.bootstrap @ core.js:5741
(anonymous) @ core.js:5461
PlatformRef._moduleDoBootstrap @ core.js:5461
(anonymous) @ core.js:5382
ZoneDelegate.invoke @ zone.js:392
onInvoke @ core.js:4630
ZoneDelegate.invoke @ zone.js:391
Zone.run @ zone.js:142
(anonymous) @ zone.js:873
ZoneDelegate.invokeTask @ zone.js:425
onInvokeTask @ core.js:4621
ZoneDelegate.invokeTask @ zone.js:424
Zone.runTask @ zone.js:192
drainMicroTaskQueue @ zone.js:602
Promise resolved (async)
scheduleMicroTask @ zone.js:585
ZoneDelegate.scheduleTask @ zone.js:414
Zone.scheduleTask @ zone.js:236
Zone.scheduleMicroTask @ zone.js:256
scheduleResolveOrReject @ zone.js:871
ZoneAwarePromise.then @ zone.js:981
PlatformRef.bootstrapModule @ core.js:5448
(anonymous) @ main.ts:11
../../../../../src/main.ts @ main.bundle.js:254
__webpack_require__ @ inline.bundle.js:55
0 @ main.bundle.js:269
__webpack_require__ @ inline.bundle.js:55
webpackJsonpCallback @ inline.bundle.js:26
(anonymous) @ main.bundle.js:1
localhost/:1 Failed to load http://localhost:8000/lancamentos?resumo: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8000' that is not equal to the supplied origin. Origin 'http://localhost:4200' is therefore not allowed access.
core.js:1350 ERROR Error: Uncaught (in promise): Response with status: 0 for URL: null
at resolvePromise (zone.js:824)
at resolvePromise (zone.js:795)
at eval (zone.js:873)
at ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (core.js:4621)
at ZoneDelegate.invokeTask (zone.js:424)
at Zone.runTask (zone.js:192)
at drainMicroTaskQueue (zone.js:602)
at ZoneTask.invokeTask [as invoke] (zone.js:503)
at invokeTask (zone.js:1540)
Esse foi do firefox
Requisição cross-origin bloqueada: A política de mesma origem (Same Origin Policy) impede a leitura do recurso remoto em http://localhost:8000/lancamentos?resumo. (Motivo: o cabeçalho CORS 'Access-Control-Allow-Origin' é incompatível com 'http://localhost:8000').
ERROR
Error: Uncaught (in promise): Response with status: 0 for URL: null
Stack trace:
resolvePromise@webpack-internal:///../../../../zone.js/dist/zone.js:824:31
resolvePromise@webpack-internal:///../../../../zone.js/dist/zone.js:795:17
scheduleResolveOrReject/<@webpack-internal:///../../../../zone.js/dist/zone.js:873:17
ZoneDelegate.prototype.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:425:17
onInvokeTask@webpack-internal:///../../../core/esm5/core.js:4817:24
ZoneDelegate.prototype.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:424:17
Zone.prototype.runTask@webpack-internal:///../../../../zone.js/dist/zone.js:192:28
drainMicroTaskQueue@webpack-internal:///../../../../zone.js/dist/zone.js:602:25
ZoneTask.invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:503:21
invokeTask@webpack-internal:///../../../../zone.js/dist/zone.js:1540:9
globalZoneAwareCallback@webpack-internal:///../../../../zone.js/dist/zone.js:1566:17
core.js:1350
Aceito sugestões.