javascript - angular 7 不按要求发送 header

标签 javascript angular http http-headers angular7

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

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

PS:当我用 postman 发送请求时,这工作正常。而且,后端代码已经使用 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)))
          }
        }

最佳答案

要使用新的 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. 调用 API this.http.post<Datatype>(API url, Bady Parameter, httpOptions)

关于javascript - angular 7 不按要求发送 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55095745/

相关文章:

node.js - 不同路径上的多个 socket.io 实例

javascript - 如何在MeanJS中启用和使用 '_'?

javascript - 为什么模态框不会慢慢淡出?

javascript - 根据父元素类型格式化json

angular - 无法将提交推送到远程 GitHub

javascript - 用 SVG 图形替换 mat-icon

javascript - Chrome 上的 Firebug Lite 导致页脚问题,有解决办法吗?

javascript - rxJs 过滤器列表,具有基于 angular4 中发出的值的去抖功能

c# - 使用 RestSharp 时如何惯用地处理 HTTP 错误代码?

http - Cache-Control :private, s-maxage=0 应该如何处理 AJAX 请求?