【问题标题】:Angular2 : detect error from HTTP postAngular2:检测来自 HTTP 帖子的错误
【发布时间】:2016-09-28 04:40:24
【问题描述】:

我无法从 http 帖子中截取错误

我的 mservice 的一部分(http post 方法)

addApplicationLink(applicationLink: ApplicationLink){
    let body = JSON.stringify(applicationLink);
    let requestHeaders = new Headers();
    var headers = new Headers();
    headers.set('Content-Type',  ['application/json; charset=utf-8']);
     let reqoptions =  new RequestOptions({
        headers: headers
    });
    return this._http.post(this._applicationLinksUrl + this._linkServicePath,body,{headers: headers});

在我的组件中:

addApplicationLink() {
    //todo
    this.addNewLink = false;
    /* check if must be done after call real rest service */
    //this.applicationLinks.push(this.applicationLinkAdd);
    this._applicationLinkService.addApplicationLink(this.applicationLinkAdd)

        .subscribe(data => {
            this.applicationLinks.push(this.applicationLinkAdd)
        },
        error => {
            // handle error
            console.error('this an erreor ' + error.status)
        }
        )

当用户尝试添加两个相同的应用程序链接时,后端返回错误 409 但是当我执行时,error.status 在浏览器控制台中显示 200 我也在浏览器控制台中看到 XMLHttpRequest 无法加载 http://localhost:7001...... 请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:3000' 不允许访问。响应的 HTTP 状态代码为 409。

rem : Http post 是用 json 制作的,因此有一个 prefligth 调用

你有拦截错误 409 的想法吗?

【问题讨论】:

  • 如果你的服务是用 NodeJS 和 Express 制作的,那么你可以使用这个 gem:npmjs.com/package/cors

标签: http error-handling angular


【解决方案1】:

事实上,您的服务器不会发回 CORS 标头(缺少 Access-Control-Allow-Origin 标头)。这可以防止浏览器向浏览器中的 Angular2 应用程序提供实际的 409 错误。

您需要先修复服务器上的问题,然后才能看到这个 409 错误。

有关 CORS 工作原理的更多详细信息,您可以查看这篇文章:

【讨论】:

  • 我发现了问题,对于响应 409 ,标头未设置。谢谢
猜你喜欢
  • 1970-01-01
  • 2016-04-29
  • 2017-05-25
  • 1970-01-01
  • 2017-02-09
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多