Nestjs發送x-www-form-urlencoded風格的請求

Nestjs的Http模塊

Nestjs的HttpModule模塊打包了Axios並且暴露出HttpService接口,HttpService將Axios數據轉換為Obervable並返回。比如,HttpService的Post方法在Nestjs源碼中是這樣寫的。

<code>  post(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Observable<axiosresponse>> {
return defer(() => this.instance.post(url, data, config));
}/<axiosresponse>
/<code>

默認情況下,HttpService發送的是JSON風格的請求,但是我們難免要和一些x-www-form-urlencoded風格的API打交道(我是在使用墨跡天氣的API時遇到這個坑的)。因為Nestjs僅僅是對Axios進行了封裝,因此要到Axios中找答案。

Axios官方說明

在Axois官方文檔中對使用x-www-form-urlencoded format風格針對瀏覽器和node環境分別做了如下說明。

  • 瀏覽器環境在瀏覽器中,可以使用URLSearchParamsAPI接口。需要注意的是並不是所有瀏覽器都支持URLSearchParams,所以可能需要polyfill一下。
    javascript const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params);在瀏覽器中也可以使用qs庫
    javascript const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 }));或者使用ES6風格的qs.
    TypeScript //這是官方文檔的寫法,但是我在nestjs中用import會報找不到模塊的錯誤,需要改成 //import * as qs from 'qs' //不確定瀏覽器中是否可以正常使用 import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options);
  • nodejs環境
    在nodejs中,可以使用querystring或者qs模塊,但是早期版本的querystring存在一些問題,因此官方推薦使用qs模塊。

    javascript //官方文檔,未做驗證 const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

NestJs中的使用

按照Axios官方文檔的推薦,使用qs庫,由於qs在axios中封裝,而Nestjs封裝了Axois,因此不需要額外安裝Axios或者qs就能直接使用。以墨跡天氣的API接口為例,token和APPCODE需要換成相應內容即可正常使用。

<code>import { Injectable, HttpService, Header } from '@nestjs/common';
import { map } from 'rxjs/operators';
import * as qs from 'qs';

@Injectable()
export class WeatherService {
constructor(private httpService: HttpService) {}

getWeatherId(id) {
const data = { cityId: id,token:**************** };
return this.httpService
.post(
'http://aliv18.data.moji.com/whapi/json/alicityweather/forecast15days',
qs.stringify(data),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
Authorization: 'APPCODE *******************',
},
},
)
.pipe(map(response => response.data));
// return this.httpService(options).pipe(
// map(response=>response.data)
// );
}/<code>


分享到:


相關文章: