Angular4 http服务400报错

来源:互联网 发布:ubuntu 安装kde桌面 编辑:程序博客网 时间:2024/06/05 15:04

400报错并不陌生,也就是前后台参数不匹配的原因,知道问题是什么接下来就开始找错误
后台代码接收参数使用的是@RequestParam String username`
@RequestParam接受Content-Type: application/x-www-form-urlencoded
而我们看下前台传数据时使用的Content-Type
这里写图片描述

咦龟龟 Content-Type哪去了?
赶紧去官网找API,看看有没有配置Headers的
在http的API中发现了RequestOptions这个配置属性我们看下RequestOptions里是什么鬼

class RequestOptions {  constructor(opts: RequestOptionsArgs = {})  method: RequestMethod|string|null  headers: Headers|null  body: any  url: string|null  params: URLSearchParams  get set search(params: URLSearchParams)  withCredentials: boolean|null  responseType: ResponseContentType|null  merge(options?: RequestOptionsArgs): RequestOptions}

终于看到了对我们有用的headers params这两个属性这里就不再往下介绍他们详细的API了,大家可以自行去API里找。
到此就是我解决这个问题的思路,勉勉强强算是解决啦,皆大欢喜~~

下面就附上解决代码

import {URLSearchParams} from '@angular/http';import {Http, Headers, RequestOptions} from '@angular/http';headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });let _data = createPostSearchParams(data);let options = new RequestOptions({ headers: this.headers, search: _data });function createPostSearchParams(searchData){  const data = new URLSearchParams();  for(let key in searchData) {    data.append(key, searchData[key])  }  return data;}this.http.get(url, options).subscribe()

这里写图片描述

现在就有Content-Type了

关于为什么Angular4为什么会多了这么多的配置项的东西
API里给到了一些提示
This class is based on the RequestInit description in the Fetch Spec.
也就是说Angular应该是基于Fetch的,关于Fetch的API大家自行搜索吧,博主也没有很好的研究过,有机会一起分享下

原创粉丝点击