diff --git a/src/main.js b/src/main.js index bf302b5..7c43d00 100644 --- a/src/main.js +++ b/src/main.js @@ -80,8 +80,16 @@ export const generateHeader = (options = {}) => { } /** - * - * + * @export + * @param {Object} body + * @returns {string} + */ +export function escapeBody(body) { + if (typeof body !== 'string') return body + return body.replace(/'/g, `'\\''`) +} + +/** * @export * @param {Object} body * @returns {string} @@ -89,14 +97,12 @@ export const generateHeader = (options = {}) => { export function generateBody(body) { if (!body) return ''; if (typeof body === "object"){ - return ` --data-binary '${JSON.stringify(body)}'`; + return ` --data-binary '${escapeBody(JSON.stringify(body))}'`; } - return ` --data-binary '${body}'`; + return ` --data-binary '${escapeBody(body)}'`; } /** - * - * * @export * @param {boolean} isEncode * @return {string} @@ -106,8 +112,6 @@ export function generateCompress(isEncode) { } /** - * - * * @export * @param {string|object} requestInfo * @param {object={}} requestInit diff --git a/test/main.test.js b/test/main.test.js index d2028e6..c9a5f1c 100644 --- a/test/main.test.js +++ b/test/main.test.js @@ -180,10 +180,11 @@ describe('Generate body param', () => { const options = { test: 'test:', testNumber: 12345, - testDate: new Date(1609251707077) + testDate: new Date(1609251707077), + testQuotes: `'test'` }; expect(generateBody(options)).toEqual( - ' --data-binary \'{"test":"test:","testNumber":12345,"testDate":"2020-12-29T14:21:47.077Z"}\'' + ` --data-binary '{"test":"test:","testNumber":12345,"testDate":"2020-12-29T14:21:47.077Z","testQuotes":"'\\''test'\\''"}'` ); }); });