如何使用来自@angular/http 的http 发送post 请求

Posted

技术标签:

【中文标题】如何使用来自@angular/http 的http 发送post 请求【英文标题】:how to send post request using http from @angular/http 【发布时间】:2018-04-15 09:38:37 【问题描述】:

我正在使用以下代码发送一个帖子请求

import  Http, Headers, Response  from '@angular/http';

@Injectable()
export class AuthenticationService 
    private _options = new Headers('Content-Type': 'application/json');
    
    constructor(private http: Http)  

    login(username: string, password: string) 
           return this.http.post('http://localhost:56451/map',
               "username": username, "password": password ,
              this._options);
    

但是我在 vscode 中遇到以下错误

Argument of type ' headers: HttpHeaders; ' is not assignable to parameter of type 'RequestOptionsArgs'. Types 
 of property 'headers' are incompatible. Type 'HttpHeaders' is not assignable to type 'Headers'. Property 'forEach' 
 is missing in type 'HttpHeaders'.

请帮助澄清相关概念

【问题讨论】:

如果您使用 angular 4 new Headers( 'Content-Type': 'application/json' );,请使用来自 @angular/http 的标头而不是 HttpHeaders 那是另一个问题,我在 SO 上看到过几个关于这个的问题,搜索它你肯定会得到答案! 我想你会得到 403,因为你在 POST 请求中提供标头,所以 Angular 首先发送一个 OPTIONS 请求,你的服务器端逻辑没有设置。您需要在服务器上启用 CORS,否则您将获得 403/405。 请根据上述 cmets 的调查结果更新您的问题 this.options 定义在哪里? 【参考方案1】:

您正在混合课程:HttpHeadersHttpClient 一起使用,替换 Http 自 4.3 起。

关于 403 的其他 cmets 值得研究,但至少要这样做:

import  HttpClient, HttpHeaders  from "@angular/common/http";
import  Observable  from 'rxjs/Observable';
import 'rxjs/add/operator/map'

@Injectable()
export class AuthenticationService 
    private _options =  headers: new HttpHeaders( 'Content-Type': 'application/json' ) ;

    // Inject HttpClient, not Http
    constructor(private http: HttpClient)  

    login(username: string, password: string) 
           return this.http.post('http://localhost:56451/map',
               username, password ,
              this._options);
    

请注意,您可以在帖子正文中使用destructuring assignment(当您的对象键名与您要替换的变量名相同时)。

【讨论】:

感谢您的回答@msanford,我正在努力,将在我找到解决方案时更新 正在处理它,也许这个链接在这里是相关的***.com/questions/33660712/… 当我将 Http 更改为 HttpClient 时,在控制台中出现以下错误,没有 HttpClient 的提供者,请您对相关概念有所了解 @AkshayVijayJain 您需要将HttpClientModule 包含在@NgModuleimports: [] 列表中。 或者有没有其他方法或文档,来确定哪个模块包含我们正在尝试使用的组件【参考方案2】:

我的问题是由于 CORS,即使我启用了 CORS chrome 插件,仍然因为我指定了选项,预检响应被发送到服务器被拒绝

有帮助的解决方案是用 Java 将 CORS 注释放在我的 rest 控制器上,所以可能只有服务器端代码可以在这里提供帮助

@CrossOrigin(origins = "*")  <------ this solved the issue of post request getting failed
@RestController
public class ProductController ...

【讨论】:

我使用 angular 和 asp.net core web api 。我还启用了 cors 。获取请求成功,但发布请求给了我 CORS 错误访问被拒绝。任何想法_谢谢

以上是关于如何使用来自@angular/http 的http 发送post 请求的主要内容,如果未能解决你的问题,请参考以下文章

来自 C# 控制器的 Angular http post formData 不受支持的媒体类型

Angular 2 Http 删除与 Web API REST 一起使用的标头

ionic/angular2 - 拒绝应用来自 'http://localhost:8100/build/main.css' 的样式,因为它的 MIME 类型('text/html')不受支持

尝试从 api.ipify.org 获取 IP 地址时出现 Angular HTTP 错误

Angular2 http observables - 如何使用未定义的类型

如何使用与 angular2 http 服务的保持连接