【问题标题】:SyntaxError: Unexpected token S, AngularJS, SpringSyntaxError: Unexpected token S, AngularJS, Spring
【发布时间】:2015-04-28 13:44:37
【问题描述】:

我正在建立一个必须有数据和徽标的简单注册。在测试中可以分别传输文件和数据,但是当尝试将它们一起发送时会发生以下错误:

SyntaxError: Unexpected token S
at Object.parse (native)
at qc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:14:245)
at Zb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:76:423)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:77:283
at r (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:7:302)
at Zc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:77:265)
at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:78:414)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:112:113
at n.$get.n.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:126:15)
at n.$get.n.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:123:106)

角度控制器

angular.module('EntregaJaApp').controller('EstabelecimentoController', ['$scope', '$http','Upload', function($scope, $http,Upload){

$scope.salvar = function(){
         Upload.upload({
            url: 'http://localhost:8080/site-web/gerencial/estabelecimento/salvar',
            file: $scope.picFile[0],
            method: 'POST',
            headers: {'Content-Type': 'multipart/form-data'}, // only for html5
            data: {'estabelecimento': $scope.estabelecimento}
        });
}}

弹簧控制器

@Controller
@RequestMapping("/gerencial/estabelecimento")
public class EstabelecimentoController {

@Autowired
private EstabelecimentoService estabelecimentoService;

    @RequestMapping(value = "/salvar",  method = RequestMethod.POST)
public ResponseEntity<?>  salvar(Estabelecimento estabelecimento,@RequestParam(value="file", required=false) MultipartFile file){
    try {
          byte[] bytes;

            if (!file.isEmpty()) {
                 bytes = file.getBytes();
                //store file in storage
            }

            System.out.println(String.format("receive %s from %s", file.getOriginalFilename(), estabelecimento.getNome()));
        estabelecimentoService.salvar(estabelecimento);
        return new ResponseEntity<>(MensagensGerais.SUCESSO_SALVAR,HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>((StringUtil.eVazia(e.getMessage()) ? MensagensGerais.ERRO_CONSULTAR : e.getMessage()),HttpStatus.BAD_REQUEST);
    }
}
   }

【问题讨论】:

  • 由于错误在解析中,我猜测发送到 Angular 的数据无效或它所期望的数据无效。你能展示你正在传输的内容吗?
  • 我在尝试传输{"nome":"Test"},也尝试过JSON.parse()和angular.toJson(),但是还是一样的错误。
  • 检查您的 JSON 数据是否有效...

标签: javascript angularjs spring


【解决方案1】:

您是否错过了返回类型注释?喜欢

@RequestMapping(value = "/salvar",  method = RequestMethod.POST)
@Produces(MediaType.APPLICATION_JSON)
public ResponseEntity<?>  salvar(Estabelecimento estabelecimento,@RequestParam(value="file", required=false) MultipartFile file){...}

【讨论】:

  • 可以用fiddler o wireshark 看服务器响应吗?
  • 响应头视图解析 HTTP/1.1 200 OK 服务器:Apache-Coyote/1.1 内容类型:应用程序/json 内容长度:17
  • -----WebKitFormBoundaryskA2p1hIUyDUePmY Content-Disposition: form-data; name="data" {"estabelecimento":{"nome":"aaa"}} ------WebKitFormBoundaryskA2p1hIUyDUePmY Content-Disposition: form-data;名称=“文件”; filename="mito.jpg" 内容类型:image/jpeg
【解决方案2】:

假设请求指定了一个接受标头“application/json”,似乎字符串没有正确序列化(通过 Spring?)。 Angular 1.3.x 之前的版本似乎已经很慷慨了,但是现在当响应不是正确的 JSON 时会抛出异常。我在我的应用中添加了以下回复 transformer

$httpProvider.defaults.transformResponse.unshift(function(data, headersGetter, status){
            var contentType = headersGetter('Content-Type');
            if(angular.isString(contentType) && contentType.startsWith('application/json')){
                try {
                    angular.fromJson(data);
                } catch(e){
                    var mod = '"'+data+'"';
                    try {
                        angular.fromJson(mod);
                        return mod;
                    }
                    catch(e){
                        return data;
                    }
                }
                return data;
            }
            else{
                return data;
            }
        });

它通过将 JS 字符串包装在额外的 " 中,将其转换为 JSON 字符串对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-31
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 2017-12-09
    • 1970-01-01
    • 2018-07-21
    相关资源
    最近更新 更多