gpt4 book ai didi

javascript - 当我尝试将 JSON 发送到 Spring 时,不支持内容类型 'application/json;charset=UTF-8'

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:06:10 24 4
gpt4 key购买 nike

当我将 JSON 包从 jQuery 发送到 Spring RestController 时,出现了很多错误:

Spring :

Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported]

在 Chrome 中:

POST http://localhost/post 415

(anonymous) @ main.js:11

我的 jQuery 代码:

$(document).ready(function() {

$('#go').on('click', function() {

var user = {
"name" : "Tom",
"age" : 23
};

$.ajax({
type: 'POST',
url: "http://localhost/post",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(user),
dataType: 'json',
async: true
});

});

});

我的 Spring RestController 代码:

@RestController
public class mainController {
@RequestMapping(value = "/post", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Object> postUser(@RequestBody User user){
System.out.println(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}

@RequestMapping(value = "/get", method = RequestMethod.GET)
public User getStr(){
System.out.println("-------------------------");
return new User("Tom", 56); //'Get' Check
}

}

实体用户:

@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private int age;
}

最佳答案

您使用了错误的媒体类型,即 APPLICATION_FORM_URLENCODED_VALUE 在 rest conttroller 中使用。在传递 json 请求时使用 MediaType.APPLICATION_JSON_UTF8_VALUE

@RestController
public class mainController {
@RequestMapping(value = "/post", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON,
produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public ResponseEntity<Object> postUser(@RequestBody User user){
System.out.println(user);
return new ResponseEntity<>("Success", HttpStatus.OK);
}

@RequestMapping(value = "/get", method = RequestMethod.GET)
public User getStr(){
System.out.println("-------------------------");
return new User("Tom", 56); //'Get' Check
}

}

关于javascript - 当我尝试将 JSON 发送到 Spring 时,不支持内容类型 'application/json;charset=UTF-8',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54832481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com