【问题标题】:AngularJS + Spring3.2 415 Unsupported Media Type errorAngularJS + Spring3.2 415 不支持的媒体类型错误
【发布时间】:2014-06-21 18:20:21
【问题描述】:

我正在使用 AngualrJS 和 Spring MVC3.2。我正在尝试将下面显示的简单对象发布到服务器,但我收到“415 Unspported Media Type error”。

@Entity
@Table(name="Question")
public class Question implements Serializable  {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id = 0;
    private String statement;
    private int frequency;
    private int difficulty;
    private String comment;
    private String reference;
    @Temporal(TemporalType.TIMESTAMP)
    protected Date regTime;
    @Temporal(TemporalType.TIMESTAMP)
    protected Date updTime;

    @OneToMany(mappedBy="question", fetch=FetchType.EAGER)
    @NotFound(action=NotFoundAction.IGNORE)
    private List<Answer> answers = new ArrayList<Answer>();

        //Getters and setters
}


@Entity
@Table(name="Answer")
public class Answer implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id = 0;
    private String answer;
    @Column(name="correct", columnDefinition="INT(1)")
    private boolean correct;

    @ManyToOne
    @JoinColumn(name="questionId", referencedColumnName="id")
    @NotFound(action=NotFoundAction.IGNORE)
    @JsonIgnore
    private Question question;

       //Getters and setters
}


@Controller
@RequestMapping("/question")
public class QuestionController {

  @RequestMapping(method=RequestMethod.POST)
    public @ResponseBody HttpResult submit(@RequestBody Question question) {

        HttpResult result = new HttpResult();

        //Do something here

        return result;
    }


}

services.js

$scope.submit = function(entity){
            $scope.formshow = false;
            var obj = angular.copy(entity);
            Question.save(obj, function(data){
                if (data.ok == true){
                    Question.add('success', 'Data has been saved successfully.');
                    $scope.loadData();
                } else {
                    Question.add('danger', data.msg);
                }
            });
        };

JSP 页面中的 JSON

{
    "id":0,
    "answers":[
        {
            "id":0,
            "answer":"a",
            "correct":false
        },
        {
            "id":0,
            "answer":"b",
            "correct":true
        },
        {}
    ],
    "statement":"test question",
    "frequency":0,
    "difficulty":0,
    "comment":"comment",
    "reference":"ref"
}

firebug 中的 Http 标头

Response Headers
Content-Length  1048
Content-Type    text/html;charset=utf-8
Date    Mon, 05 May 2014 12:29:56 GMT
Server  Apache-Coyote/1.1
Request Headers
Accept  application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5

我知道 415 错误意味着 http 标头内容类型错误或请求数据格式无效。 我曾尝试强制更改 http 标头类型,但无法更改。我该如何解决? 您的回答将不胜感激。

【问题讨论】:

  • 看一下:[link][1][1]:stackoverflow.com/questions/18102452/…希望对你有帮助
  • 您似乎没有将 json 发送到服务器 Content-Type text/html;charset=utf-8
  • 粉丝。谢谢,我认为这是一个类似的情况,但不是我的情况。 AngularJS 标头的默认内容类型是 json,我没有触及任何内容。
  • geoand.我试图更改标题但不能。 var http = $http.post('url_to_server', arg, {headers: {'Content-Type': 'application/json'}});另外,AngularJS 默认的 Content-Type 是 'application/json' $httpProvider.defaults.headers.post

标签: angularjs spring-mvc


【解决方案1】:

事实上,默认的 Content-Type 是 application/json,但是您发送的是 text/html。我知道,到目前为止对你来说没有什么新鲜事。

从 1.1.1 版开始(如果我没记错的话),您可以在 $resource 定义中强制执行内容类型。

您可以尝试像这样定义您的 $resource:

    var Question = $resource('your/resource/url',{your params if any, otherwise send this as an empty object},{
       post: {
           method:'POST',
           isArray: false,
           headers: {'Content-Type': 'application/json;charset=UTF-8'}
       }
} )

然后,使用 Question.post(...) 代替 Question.save()。我创建了 post 方法只是为了让您不会丢失 save() 默认行为...但是您可以像配置 post 方法一样配置 save 方法。

P.S.:此代码未经测试。

【讨论】:

  • 谢谢。最后我知道真正的问题是什么。这是我的错,我在按钮 onclick 事件中传递了拼写错误的变量。
  • 它总是在小细节中:)
猜你喜欢
  • 2014-10-02
  • 1970-01-01
  • 2018-10-13
  • 2018-07-25
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-04
相关资源
最近更新 更多