Angular4 http服務400報錯

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大家自行搜索吧,博主也沒有很好的研究過,有機會一起分享下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章