You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Call Mediator与Script Mediator构建WSO2 API时出现格式兼容错误的求助

问题排查与解决方案

首先,你遇到的Unexpected character in preface '{' (code 123); expected '<'错误,核心原因是WSO2 Synapse默认会把消息体按XML格式解析,但Call Mediator返回的是JSON数据,且你没有明确告知Synapse当前消息类型是JSON,导致后续处理时底层试图把JSON当作XML解析——JSON以{开头,而XML要求以<开头,自然就触发了格式不匹配的错误。

另外你的Script Mediator还有个逻辑小问题:从目标接口获取的是用户数组(不是单个用户对象),所以直接用x.id会返回undefined,永远走else分支返回{"s":"error"},这也需要一起修正。

1. 先解决消息类型不匹配问题

在Call Mediator之后,添加一个property Mediator,明确设置messageType为application/json,告诉Synapse当前消息体是JSON格式:

<property name="messageType" value="application/json" scope="axis2"/>

2. 修正Script Mediator的逻辑错误

因为返回的是用户数组,你需要调整判断逻辑,比如检查数组中是否存在id为1的用户,示例代码如下:

var users = mc.getPayloadJSON();
// 检查数组里有没有id=1的用户
var hasTargetUser = users.some(user => user.id === 1);
if (hasTargetUser) {
    mc.setPayloadJSON({"s":"success"});
} else {
    mc.setPayloadJSON({"s":"error"});
}

修正后的完整API配置

<?xml version="1.0" encoding="UTF-8"?>
<api context="/x" name="x" xmlns="http://ws.apache.org/ns/synapse">
  <resource methods="GET">
    <inSequence>
      <call>
        <endpoint>
          <http method="get" uri-template="https://jsonplaceholder.typicode.com/users">
            <suspendOnFailure>
              <initialDuration>-1</initialDuration>
              <progressionFactor>-1</progressionFactor>
              <maximumDuration>0</maximumDuration>
            </suspendOnFailure>
            <markForSuspension>
              <retriesBeforeSuspension>0</retriesBeforeSuspension>
            </markForSuspension>
          </http>
        </endpoint>
      </call>
      <!-- 指定消息类型为JSON,避免XML解析错误 -->
      <property name="messageType" value="application/json" scope="axis2"/>
      <script language="js"><![CDATA[
var users = mc.getPayloadJSON();
var hasTargetUser = users.some(user => user.id === 1);
if (hasTargetUser) {
    mc.setPayloadJSON({"s":"success"});
} else {
    mc.setPayloadJSON({"s":"error"});
}
]]></script>
      <respond/>
    </inSequence>
    <outSequence/>
    <faultSequence/>
  </resource>
</api>

验证说明

  • 添加messageType属性后,Synapse会正确识别消息体为JSON,不会再触发XML解析错误;
  • 修正后的Script逻辑会正确检查返回的用户数组,符合你的业务判断需求。

内容的提问来源于stack exchange,提问作者Yusuf UZUN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:27:37