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

使用AWS SAM配置AppSync JS解析器遇JSON格式错误求助

原配置的问题分析

核心错误原因

你遇到的Unrecognized token 'util'错误,本质是混淆了AppSync VTL模板与JS解析器的SAM配置规则,导致AppSync把JS代码当成JSON格式解析,触发语法错误。

具体问题点

  1. 配置字段误用
    原配置错误使用了RequestMappingTemplate和ResponseMappingTemplate字段——这两个字段是专门为VTL(Velocity Template Language)解析器设计的,AppSync会默认尝试将字段内容解析为JSON格式(或VTL字符串)。而你在其中写入了JS解析器代码(包含util.*这类JS语法),这些内容不符合JSON语法规范,自然触发解析错误。

  2. JS解析器的正确配置逻辑
    AWS AppSync支持JS解析器后,SAM配置需要改用专门的JS解析器字段:

    • 必须指定Runtime字段,声明使用的JS运行时版本(例如{"Name": "APPSYNC_JS", "RuntimeVersion": "1.0.0"})
    • 通过Code字段(InlineCode或S3Location)传入JS解析器代码,而非VTL模板字段

原配置的典型错误示例(对比修正版)

原配置可能类似:

AddUserResolver:
  Type: AWS::AppSync::Resolver
  Properties:
    ApiId: !Ref MyApi
    TypeName: Mutation
    FieldName: addUser
    RequestMappingTemplate: |
      import { util } from '@aws-appsync/utils';
      export function request(ctx) {
        return {
          operation: 'PutItem',
          key: util.dynamodb.toMapValues({ id: util.autoId() }),
          attributeValues: util.dynamodb.toMapValues(ctx.args.input)
        };
      }
    ResponseMappingTemplate: |
      export function response(ctx) {
        return ctx.result;
      }

这种写法会触发错误,因为RequestMappingTemplate的内容被AppSync当作JSON解析,而import、util等不是合法JSON token。

修正后的配置应该改用JS解析器的正确字段:

AddUserResolver:
  Type: AWS::AppSync::Resolver
  Properties:
    ApiId: !Ref MyApi
    TypeName: Mutation
    FieldName: addUser
    Runtime:
      Name: APPSYNC_JS
      RuntimeVersion: 1.0.0
    Code:
      InlineCode: |
        import { util } from '@aws-appsync/utils';
        export function request(ctx) {
          return {
            operation: 'PutItem',
            key: util.dynamodb.toMapValues({ id: util.autoId() }),
            attributeValues: util.dynamodb.toMapValues(ctx.args.input)
          };
        }
        export function response(ctx) {
          return ctx.result;
        }

内容的提问来源于stack exchange,提问作者salt-pepper

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:16:05