From b1a5062eb6fc4a6dd1c01ae61280c9736a370d9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E4=BC=9F?= Date: Tue, 18 Feb 2025 11:31:08 +0800 Subject: [PATCH] fix: When the HTTP request body is in JSON format, the request may fail if there are line breaks or unescaped double quotes. --- api/core/workflow/entities/variable_pool.py | 14 ++++++++++++++ api/core/workflow/nodes/http_request/executor.py | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/api/core/workflow/entities/variable_pool.py b/api/core/workflow/entities/variable_pool.py index 844b46f352..79788495f0 100644 --- a/api/core/workflow/entities/variable_pool.py +++ b/api/core/workflow/entities/variable_pool.py @@ -167,6 +167,20 @@ class VariablePool(BaseModel): segments.append(variable_factory.build_segment(part)) return SegmentGroup(value=segments) + def convert_template_escape(self, template: str, /): + parts = VARIABLE_PATTERN.split(template) + segments = [] + for part in filter(lambda x: x, parts): + if "." in part and (variable := self.get(part.split("."))): + if isinstance(variable.value, str): + escape_string = variable.value.replace('"', '\\"').replace('\n', '\\n') + segments.append(variable_factory.build_segment(escape_string)) + else: + segments.append(variable) + else: + segments.append(variable_factory.build_segment(part)) + return SegmentGroup(value=segments) + def get_file(self, selector: Sequence[str], /) -> FileSegment | None: segment = self.get(selector) if isinstance(segment, FileSegment): diff --git a/api/core/workflow/nodes/http_request/executor.py b/api/core/workflow/nodes/http_request/executor.py index 5ed2cd6164..d32bf9c8d3 100644 --- a/api/core/workflow/nodes/http_request/executor.py +++ b/api/core/workflow/nodes/http_request/executor.py @@ -172,7 +172,7 @@ class Executor: case "json": if len(data) != 1: raise RequestBodyError("json body type should have exactly one item") - json_string = self.variable_pool.convert_template(data[0].value).text + json_string = self.variable_pool.convert_template_escape(data[0].value).text try: json_object = json.loads(json_string, strict=False) except json.JSONDecodeError as e: