Cross-Origin Request Blocked Angular 4,POST Request

时间:2018-09-18 19:53:31

标签: angular post cors cross-domain credentials

I'm working on a register form using Angular 4 and an authentication REST API in Springboot. When I submit the form, I get this error:

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)

I think the problem is on the head of the request. When I inspect the request on the browser I get this:

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  

This is my Angular code :

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 of the 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 :(得分:2)

我将以下过滤器添加到后端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);
        }
    }