本地主机api请求的HTTP失败响应:0未知错误-Angular

时间:2019-03-21 23:15:23

标签: java angular jetty

我正在尝试从Angular应用程序创建到Java Jetty后端的通信。当我尝试执行请求时,出现以下错误:

Error on request

我在客户端的代码:(角度7.2.1)。我还在使用HttpInterceptor进行身份验证,该方法应该可以正常工作。我还在ng serve的开发模式下运行代码。

@Injectable({
    providedIn: 'root'
})
export class NgHydrantService {

    constructor(private http: HttpClient) {
    }
  
    public register(entity: IEntityDescription): Observable<StandardResponsePacket> {
        let packet = new RegisterEntityRequestPacket(entity);
        return this.http.post(this._apiUrl, packet.toJson())
            .pipe(
                map(value => {
                    console.log('register result:', value); //<-- never executed
                    return <StandardResponsePacket>HydrantPackage.fromJson(value)
                })
            );

    }
}

//The interceptor
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // add authorization header with basic auth credentials if available
        if (this.user != null) {

            const clonedRequest = request.clone({
                headers: request.headers.set('Authorization', `Basic ${this.user.getAuth()}`)
                                        .set('Accept','application/json')
            });
            //This debug line works and looks good!
            console.log('NgHydrantAuthInterceptor#intercept', clonedRequest);
            return next.handle(clonedRequest);
        }

        return next.handle(request);
    }

我在服务器端的代码:(Jetty-9.4.14.v20181114)在本地主机上运行。

public final class PacketHandler extends AbstractHandler
{
  @Override
  public void handle( String target,
                    Request baseRequest,
                    HttpServletRequest request,
                    HttpServletResponse response ) throws IOException
  {
    try
    {
        // Declare response encoding and types
        response.setContentType( "application/json; charset=utf-8" );
        // Enable CORS
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
        response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
        response.addHeader("Access-Control-Max-Age", "1728000");
        //... more stuff
    }
    finally
    {
        // Inform jetty that this request was handled
        baseRequest.setHandled( true );
    }
  }
}

我检查过的事情:

  • 在研究过程中,有些人引用了CORS的问题(这就是为什么我在服务器端代码中添加标头条目的原因)
  • Postman中的相同请求可以正常工作
  • 服务器端没有日志

我的问题是有关在开发过程中从服务器获取响应的可能解决方案。

2 个答案:

答案 0 :(得分:0)

请按照以下链接中的步骤进行操作 https://www.html5rocks.com/en/tutorials/cors/ 为了快速解决方案,请在Chrome中添加以下插件 https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

答案 1 :(得分:0)

我可以通过将Web服务器配置设置为允许cors策略来解决可能的问题。就我而言,我使用Nginx Web服务器遵循此链接https://enable-cors.org/server_nginx.html

中的配置