Angular 交叉原点请求阻塞角度4,POST请求

Angular 交叉原点请求阻塞角度4,POST请求,angular,post,cors,cross-domain,credentials,Angular,Post,Cors,Cross Domain,Credentials,我正在使用Angular 4和Springboot中的认证REST API编写一个注册表表单。当我提交表单时,出现以下错误: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/authentification-ws/authentification/register. (Reason: CORS request di

我正在使用Angular 4和Springboot中的认证REST API编写一个注册表表单。当我提交表单时,出现以下错误:

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");
      }
    );
  }

}
从'@angular/core'导入{Injectable};
从'@angular/common/http'导入{HttpClient,HttpHeaders};
从'rxjs/Observable'导入{Observable}
从“/IUser”导入{IUser};
常量httpOptions={
标题:新的HttpHeaders({
“内容类型”:“应用程序/json”,
//“授权”:“我的身份验证令牌”
}),
证书:正确
};
@可注射()
导出类注册服务{
专用注册表rpiURL=”http://localhost:8080/authentification-ws/authentification/register”;
私人用户:IUser={
姓名:“艾哈迈德”,
电子邮件:“艾哈迈德。hlissa@gmail.com',
密码:“1234560”
};
构造函数(私有http:HttpClient){}
寄存器(){
this.http.post(this.registerApiUrL,this.user,httpOptions)。订阅(
res=>{
控制台日志(res);
},
错误=>{
console.log(“致命错误”);
}
);
}
}
API的Web.xml文件:

<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>

克斯菲尔特
org.apache.catalina.filters.CorsFilter
科尔斯
*
cors.methods
获取、发布、头部、选项、放置
cors.allowed.headers
内容类型、X-Requested-With、accept、Origin、访问控制请求方法、访问控制请求标头
cors.exposed.headers
访问控制允许来源,访问控制允许凭据
cors.support.credentials
真的
cors.preflight.maxage
10
克斯菲尔特
/*

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

能否指定部署webApi的服务器?您需要在API端启用cors。我认为在前端没有什么可做的。您是否缺少授权标题中的“承载者”授权“:“我的授权令牌持有人”??当我的API抛出异常时,我也遇到了Cors错误。@JFPicard我正在使用tomcat9server@RajKarri我认为它是在web.xml中启用的:cors.support.credentials是真的