localhost api请求的Http失败响应:0未知错误 - 角度

问题描述 投票:0回答:2

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

Error on request

我在客户端的代码:(Angular 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的问题(这就是为什么我在服务器端代码中添加了头条目)
  • 邮差中的相同请求没有任何问题
  • 服务器端没有日志

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

java angular jetty
2个回答

0
投票

通过设置我的Web服务器配置以允许cors策略,我能够解决可能的问题。在我的情况下,我使用Nginx Web服务器按照此链接https://enable-cors.org/server_nginx.html中的配置

© www.soinside.com 2019 - 2024. All rights reserved.