CORS support with Angular + Rest (Java)

Attempting to access a Rest server (Java) with a different domain from an Angular client will result in an error due to a CORS issue. The countermeasures are described below. (The Rest API processing on the server side is the same as usual, so it will be omitted.)

Processing to request to the server on the Angular side

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class ClientService {
  url = "http://XXXXX:XXXX/XXXXX"; //Access destination

  returnModel : ReturnModel; //Return value from the server

  //constructor
  constructor(private http: HttpClient) {}

  //Send method
  request(): void {
    //Http header(Access with CORS-Control-Allow-Specify Origin)
    const httpOptions = {
      headers: new HttpHeaders({
        'Access-Control-Allow-Origin': '*',
      })
     };

    //Transmission data
    const data = new HttpParam({
      fromObject: {
        value: '1000"
      }
    });

    //POST to server
    this.http.post<ReturnModel>(this.url , data, httpOptions).subscribe(h => this.returnModel = h);
  }
}

Server-side Servlet Filter

package sample.filter;

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.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

//Servlet filter
@WebFilter(filterName = "CorsFilter", urlPatterns = { "/*" })
public class CorsFilter implements Filter {
  @Override
  public void init(FilterConfig config) {
  }

  //Filtering
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (response instanceof HttpServletResponse) {
      //Specify Headerwo for CORS support as follows
      HttpServletResponse http = (HttpServletResponse) response;
      http.addHeader("Access-Control-Allow-Origin", "*");
      http.addHeader("Access-Control-Allow-Headers", "*");
      http.addHeader("Access-Control-Allow-Credentials", "true");
      http.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
    chain.doFilter(request, response);
  }

  @Override
  public void destroy() {
  }
}

Recommended Posts

CORS support with Angular + Rest (Java)
SonarQube Java 11 support
Java support period
Java8, 9, 10 support period
Change seats with java
Install Java with Ansible
Comfortable download with JAVA
Download Java with Ansible
About Java 10 Docker support
Lombok's Java 9+ support story
Let's scrape with Java! !!
Build Java with Wercker
Summary of Java support 2018
Endian conversion with JAVA
[Java / Kotlin] Escape (sanitize) HTML5 support with unbescape [Spring Boot]
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java
Java multi-project creation with Gradle
Getting Started with Java Collection
Java Config with Spring MVC
Basic Authentication with Java 11 HttpClient
Let's experiment with Java inlining
Run batch with docker-compose with Java batch
[Template] MySQL connection with Java
Rewrite Java try-catch with Optional
Install Java 7 with Homebrew (cask)
[Java] JSON communication with jackson
Java to play with Function
Try DB connection with Java
[Java] JavaConfig with Static InnerClass
Try gRPC with Java, Maven
Let's operate Excel with Java! !!
Version control Java with SDKMAN
RSA encryption / decryption with java 8
Paging PDF with Java + PDFBox.jar
Sort strings functionally with java
Object-oriented (java) with Strike Gundam
Java version control with jenv
Troubleshooting with Java Flight Recorder
Streamline Java testing with Spock
Connect to DB with Java
Connect to MySQL 8 with Java
Error when playing with java
Using Mapper with Java (Spring)
Java study memo 2 with Progate
REST API testing with REST Assured
Getting Started with Java Basics
Seasonal display with Java switch
Use SpatiaLite with Java / JDBC
Study Java with Progate Note 1
Compare Java 8 Optional with Swift
HTML parsing with JAVA (scraping)
Run Java VM with WebAssembly
Screen transition with swing, java
Java unit tests with Mockito