gpt4 book ai didi

java - localhost api 请求的 Http 失败响应 : 0 Unknown Error - Angular

转载 作者:行者123 更新时间:2023-11-30 05:43:16 27 4
gpt4 key购买 nike

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

Error on request

我在客户端的代码:(Angular 7.2.1)。我还使用 HttpInterceptor 进行身份验证,应该可以工作。我还在开发模式下使用 ngserve 运行代码。

@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 的问题(这就是我在服务器端代码中添加 header 条目的原因)
  • 在 Postman 中执行相同的请求没有任何问题
  • 服务器端没有日志

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

最佳答案

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

关于java - localhost api 请求的 Http 失败响应 : 0 Unknown Error - Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55290608/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com