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