首页 > 解决方案 > 角度 7 未按要求发送标头

问题描述

我正在尝试为以下发布请求发送内容类型标头以允许 json 请求,但它向我抛出了一个错误Invalid CORS request with OPTIONS request method。它甚至不发送POST方法。

在这里,我无法使用RequestOptions折旧的。

PS:当我用邮递员发送请求时,这工作正常。而且,后端代码已经通过 CORS 请求处理。

从后端java代码,这是我得到的错误

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

我在哪里失踪?

 postSubmit(){

        let data = { "name":"John", "age":30 };

         const httpHeaders = new HttpHeaders ({
            'Content-Type': 'application/json'
          });

            return this.http.post<any>(apiURL, data, {headers : httpHeaders})
            .pipe(catchError(error => this.handleError(error)))
          }
        }

标签: javascriptangularhttphttp-headersangular7

解决方案


要使用新的 HttpHeaders 类定义内容类型,您需要

  1. 只需导入import { HttpHeaders } from '@angular/common/http'
  2. 创建将传递给每个 HttpClient 保存方法的 httpOptions 对象

    import { HttpHeaders } from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': 'my-auth-token' }) };

  3. 调用 APIthis.http.post<Datatype>(API url, Bady Parameter, httpOptions)


推荐阅读