diff --git a/lib/RestClient.ts b/lib/RestClient.ts index 19e6b4e6..2a033c8f 100644 --- a/lib/RestClient.ts +++ b/lib/RestClient.ts @@ -106,8 +106,16 @@ export class RestClient { let url: string = util.getUrl(resource, this._baseUrl); let headers: ifm.IHeaders = this._headersFromOptions(options, true); + let data: string; + + if (headers["Content-Type"].includes("application/json")) { + data = JSON.stringify(resources, null, 2); + } + + else { + data = resources; + } - let data: string = JSON.stringify(resources, null, 2); let res: httpm.HttpClientResponse = await this.client.post(url, data, headers); return this.processResponse(res, options); } diff --git a/test/tests/resttests.ts b/test/tests/resttests.ts index 028f4cc8..c80718fd 100644 --- a/test/tests/resttests.ts +++ b/test/tests/resttests.ts @@ -11,7 +11,8 @@ export interface HttpBinData { url: string; data: any; json: any; - args?: any + args?: any; + form: any; } describe('Rest Tests', function () { @@ -93,6 +94,19 @@ describe('Rest Tests', function () { assert(restRes.result && restRes.result.json.name === 'foo'); }); + it('creates a resource with a url encoded body', async () => { + let options: restm.IRequestOptions = { + additionalHeaders: { + 'Content-Type': 'application/x-www-form-urlencoded', + } + }; + let res: string = 'body=url%20encoded%20body'; + let restRes: restm.IRestResponse = await _restBin.create('post', res, options); + assert(restRes.statusCode == 200, "statusCode should be 200"); + assert(restRes.result && restRes.result.url === 'https://httpbin.org/post'); + assert(restRes.result && restRes.result.form.body === 'url encoded body'); + }); + it('creates a resource with a baseUrl', async() => { let res: any = { name: 'foo' }; let restRes: restm.IRestResponse = await _restBin.create('post', res); diff --git a/test/units/resttests.ts b/test/units/resttests.ts index 78c72fdc..a78edfbc 100644 --- a/test/units/resttests.ts +++ b/test/units/resttests.ts @@ -134,6 +134,29 @@ describe('Rest Tests', function () { assert(restRes.result && restRes.result.json === 'foo'); }); + it('creates a resource with a url encoded body', async () => { + nock('http://microsoft.com') + .post('/') + .reply(200, function (uri, requestBody) { + let body = decodeURI(requestBody); + return { + url: 'http://microsoft.com/post', + data: body, + json: null + }; + }); + let options: restm.IRequestOptions = { + additionalHeaders: { + 'Content-Type': 'application/x-www-form-urlencoded', + } + }; + let res: string = 'url%20encoded%20body'; + let restRes: restm.IRestResponse = await _rest.create('http://microsoft.com', res, options); + assert(restRes.statusCode == 200, "statusCode should be 200"); + assert(restRes.result && restRes.result.url === 'http://microsoft.com/post'); + assert(restRes.result && restRes.result.data === 'url encoded body'); + }); + it('creates a resource with a baseUrl', async() => { nock('http://microsoft.com') .post('/')