Угловой запрос перекрестного происхождения 4, запрос POST - PullRequest
0 голосов
/ 18 сентября 2018

Я работаю над формой регистрации с использованием Angular 4 и REST API аутентификации в Springboot.Когда я отправляю форму, я получаю эту ошибку:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/authentification-ws/authentification/register. (Reason: CORS request did not succeed)

Я думаю, что проблема в заголовке запроса.Когда я проверяю запрос в браузере, я получаю следующее:

Accept  text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Encoding   gzip, deflate
Accept-Language     en-US,en;q=0.5
Access-Control-Request-Headers  content-type
Access-Control-Request-Method   POST
Connection  keep-alive
Host    localhost:8080
Origin  http://localhost:4200
User-Agent  Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/62.0  

Это мой угловой код:

import { Injectable } from '@angular/core';

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable'
import { IUser } from './IUser';
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    //'Authorization': 'my-auth-token'
  }),
  withCredentials: true
};
@Injectable()
export class RegisterService {
  private registerApiUrL = "http://localhost:8080/authentification-ws/authentification/register";
  private user: IUser = {
    name: 'ahmed',
    email: 'ahmedd.hlissa@gmail.com',
    password: '1234560'
  };
  constructor(private http: HttpClient) { }
  register() {

    this.http.post<IUser>(this.registerApiUrL, this.user, httpOptions).subscribe(
      res => {
        console.log(res);
      },
      err => {
        console.log("Error Fatal");
      }
    );
  }

}

Web.xml API:

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

1 Ответ

0 голосов
/ 21 сентября 2018

Я добавляю фильтр ниже в бэкэнд API, и он работает:

public class CORSFilter implements Filter {
    public void destroy() {
    }

    public static String VALID_METHODS = "DELETE, HEAD, GET, OPTIONS, POST, PUT";

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws ServletException, IOException {
        HttpServletRequest httpReq = (HttpServletRequest) req;
        HttpServletResponse httpResp = (HttpServletResponse) resp;

        // No Origin header present means this is not a cross-domain request
        String origin = httpReq.getHeader("Origin");
        if (origin == null) {
            // Return standard response if OPTIONS request w/o Origin header
            if ("OPTIONS".equalsIgnoreCase(httpReq.getMethod())) {
                httpResp.setHeader("Allow", VALID_METHODS);
                httpResp.setStatus(200);
                return;
            }
        } else {
            // This is a cross-domain request, add headers allowing access
            httpResp.setHeader("Access-Control-Allow-Origin", origin);
            httpResp.setHeader("Access-Control-Allow-Methods", VALID_METHODS);
            httpResp.setHeader("Access-Control-Allow-Credentials", "true");
            String headers = httpReq.getHeader("Access-Control-Request-Headers");
            if (headers != null)
                httpResp.setHeader("Access-Control-Allow-Headers", headers);

            // Allow caching cross-domain permission
            httpResp.setHeader("Access-Control-Max-Age", "3600");
        }
        // Pass request down the chain, except for OPTIONS
        if (!"OPTIONS".equalsIgnoreCase(httpReq.getMethod())) {
            chain.doFilter(req, resp);
        }
    }
...