API on port 8000 and Angular on port 4200, how to solve?

2

My system is making a request on port 8000 aparti from localhost 4200 When a request is made by a protocol a domain on different ports of origin, which is my case the application Angular is on port 4200 the api java is on port 8000 in that case for security browsers restrict access, does not allow the request to be made, the browser itself already has this layer of security that restrict the access.

But there is a mechanism known as CORS that allows the servers to configure cross domain access control, with the protocol, with different domain or ports of the source, the backend I'm using already has the cross domain implementation, as you can see below;

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 {
}

}

But it is necessary to pass the initialization parameter of it which is the allowed origin, because by default in this case here by default it is allowing the origin: 8000

this is the parameter:

java -jar wladimir-api-1.0.0-SNAPSHOT.jar --spring.datasource.username=postgres --spring.datasource.password=1234 algamoney.origin-permitida=http://localhost:4200

When running the application it does not generate any error messages and I can even list my records by the database as you can see below;

What is the problem?

See the error message on the chrome browser consoles

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)

This was from 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

I accept suggestions.

    
asked by anonymous 13.12.2017 / 12:01

1 answer

1

For development is simple, just set up a proxy in the web-server dev-server.

See this post I made about it, briefly explain what CORS is and how to configure proxy using @angular/cli : link

Already in production will depend on how your deploy will be done.

    
13.12.2017 / 17:33