diff --git a/src/middleware/http.ts b/src/middleware/http.ts index fb07ba1c21834b196d14ae77229acbb8774ade57..549e76c6b6a4ab575d998697dbad1bddc1639406 100644 --- a/src/middleware/http.ts +++ b/src/middleware/http.ts @@ -17,6 +17,7 @@ const isObject = (field: unknown): field is Data => typeof field !== 'string' const CONTENT_TYPE = 'content-type' const JSON_TYPE = 'application/json' +const STRING_TYPE = 'text/plain' const FORM_TYPE = 'application/x-www-form-urlencoded' function initContextType(headers: Data) { @@ -98,20 +99,42 @@ export async function http(ctx: Context, next: Next) { if (ctx.config.debug === true) { ;(ret as any).stack = e.stack || '' } - return (ctx.body = { - mpserverlessComposedResponse: true, // aliyun - statusCode: 400, - headers: contentTypeHeader, - body: JSON.stringify(ret), - }) + const res = { + mpserverlessComposedResponse: true, // aliyun + statusCode: 400, + headers: contentTypeHeader + } + if( typeof(ret) == 'string' ) + { + res.body = ret + res.headers[CONTENT_TYPE] = STRING_TYPE + } + else + { + res.headers[CONTENT_TYPE] = JSON_TYPE + res.body = JSON.stringify(ret) + } + return (ctx.body = body) } const contextType = ctx.headers[CONTENT_TYPE] || JSON_TYPE - ctx.body = { + + const res = { mpserverlessComposedResponse: true, // aliyun - isBase64Encoded: !!ctx.isBase64Encoded, + isBase64Encoded: !!ctx.isBase64Encoded, statusCode: ctx.status, - headers: Object.assign(ctx.headers, { [CONTENT_TYPE]: contextType }), - body: contextType === JSON_TYPE ? JSON.stringify(ctx.body) : ctx.body, + headers: Object.assign(ctx.headers, { [CONTENT_TYPE]: contextType }) + } + if( typeof(ctx.body) == 'string' ) + { + res.body = ctx.body + res.headers[CONTENT_TYPE] = STRING_TYPE + } + else + { + res.headers[CONTENT_TYPE] = JSON_TYPE + res.body = JSON.stringify(ctx.body) } + + ctx.body = res } }