4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Angular+Rest(Java)でCORS対応

Posted at

Angularクライアントからドメインの異なるRestサーバー(Java)へアクセスしようとするとCORS問題によってエラーとなります。
その対策を以下に記述します。
(サーバー側のRest API処理は通常と変わらないため省略します)

Angular側のサーバーへリクエストする処理

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"; // アクセス先

  returnModel : ReturnModel; // サーバーからの戻り値

  // コンストラクタ
  constructor(private http: HttpClient) {}

  // 送信メソッド
  request(): void {
    // Httpヘッダー(CORS対応でAccess-Control-Allow-Originを指定する)
    const httpOptions = {
      headers: new HttpHeaders({
        'Access-Control-Allow-Origin': '*',
      })
     };

    // 送信データ
    const data = new HttpParam({
      fromObject: {
        value: '1000"
      }
    });

    // サーバーへPOST
    this.http.post<ReturnModel>(this.url , data, httpOptions).subscribe(h => this.returnModel = h);
  }
}

サーバー側の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;

// サーブレットフィルタ
@WebFilter(filterName = "CorsFilter", urlPatterns = { "/*" })
public class CorsFilter implements Filter {
  @Override
  public void init(FilterConfig config) {
  }

  // フィルター処理
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (response instanceof HttpServletResponse) {
      // 以下の通りCORS対応のためHeaderwo指定する
      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() {
  }
}
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?