Nestjs??Http???
Nestjs??HttpModule???????Axios????????HttpService????HttpService??Axios????????Obervable??????????磬HttpService??Post??????Nestjs???????????д???
post<T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Observable<AxiosResponse<T>> {
return defer(() => this.instance.post(url, data, config));
}
???????£?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???????????????????????á?
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)
// );
}