angular 7在请求中没有发送头部

24 浏览
0 Comments

angular 7在请求中没有发送头部

我试图通过发送POST请求来设置content-type头,以允许json请求,但是它抛出了一个无效的CORS请求错误,使用的是OPTIONS请求方法。甚至连POST方法都没有发送。

在这里,我不能使用已弃用的RequestOptions

PS:当我使用postman发送请求时,这个问题没有出现。而且,后端代码已经处理了CORS请求。

从后端Java代码中,我得到了以下错误:

org.springframework.web.HttpMediaTypeNotSupportedException: 不支持的内容类型 'text/plain;charset=UTF-8'

我错过了什么地方?

 postSubmit(){
        let data = { "name":"John", "age":30 };
         const httpHeaders = new HttpHeaders ({
            'Content-Type': 'application/json'
          });
            return this.http.post(apiURL, data, {headers : httpHeaders})
            .pipe(catchError(error => this.handleError(error)))
          }
        }

0
0 Comments

在Angular 7中发送请求时没有发送header的问题,可能是由于以下原因导致的:

1. 没有正确导入HttpHeaders类。可以使用以下代码导入:

import { HttpHeaders } from '@angular/common/http';

解决方法是:

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

2. 没有在HttpClient的保存方法中传递httpOptions对象。可以使用以下代码调用API:

this.http.post(API url, Body Parameter, httpOptions)

通过以上方法,可以在Angular 7中正常发送带有header的请求。

0