【发布时间】:2020-04-30 03:12:26
【问题描述】:
我有一个使用 fetch api 并使用 POST 调用 spring web 后端的 nodejs 类。
fetch(this.service, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(this.request) // body data type must match "Content-Type" header
}).then(res => res.json())
.then((result) => {
if(result.responseStatus === 'OK'){
resolve(result);
}else{
console.log("failed response");
console.log(result);
}
}, (error) => {
//handle error here
console.log("errored response");
console.log(error);
});
在后端我有这个 -
@Controller
@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "/user", method = { RequestMethod.GET,
RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE, headers = "Accept="
+ MediaType.APPLICATION_JSON_VALUE)
public class SomeController {
private final SomeDALImpl repository;
private SomeResponse response;
@Autowired
public SomeController(SomeDALImpl repo) {
this.repository = repo;
}
@RequestMapping("/abcd")
@ResponseBody
public SomeResponse getSome(@RequestBody @Valid SomeGetRequest request) {
response = new SomeResponse();
//does something
return response;
}
}
SomeGetRequest 是一个看起来像这样的类 -
public class SomeGetRequest{
public ObjectId someId;
//other getter setters
}
我正在尝试使用 gson 作为我在 spring 中的默认值,而不是 Jackson。当我从前端发送请求时,它不会反序列化来自前端的 ObjectId 请求。
在 JSON.stringify 之后从前端进入 fetch 的正文 - "{"someId":"507f1f77bcf86cd799439011"}"
在后端,这是错误 -
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver
[http-nio-8080-exec-6] Resolved [org.springframework.http.converter.HttpMessageNotReadableException:
Could not read JSON: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was
STRING at line 1 column 12 path $.userId; nested exception
is com.google.gson.JsonSyntaxException:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but
was STRING at line 1 column 12 path $.someId]
我在 application.properties 中有这个 - spring.http.converters.preferred-json-mapper = gson
我在 pom.xml 中删除了 Jackson 依赖项 -
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- Exclude the default Jackson dependency -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</exclusion>
</exclusions>
</dependency>
我也添加了这个类,但它仍然不适用于 ObjectIds -
@Configuration
public class GsonConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(customGsonHttpMessageConverter());
extendMessageConverters(converters);
}
private GsonHttpMessageConverter customGsonHttpMessageConverter() {
GsonBuilder builder = new GsonBuilder().registerTypeAdapter(ObjectId.class, new JsonSerializer<ObjectId>() {
@Override
public JsonElement serialize(ObjectId src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toHexString());
}
}).registerTypeAdapter(ObjectId.class, new JsonDeserializer<ObjectId>() {
@Override
public ObjectId deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new ObjectId(json.getAsString());
}
});
Gson gson = builder.create();
GsonHttpMessageConverter gsonMessageConverter = new GsonHttpMessageConverter();
gsonMessageConverter.setGson(gson);
return gsonMessageConverter;
}
}
或者,也许我没有从前端正确发送请求正文。我该怎么做才能纠正这个问题。谢谢,我是 Spring 新手。
PS - 在春季,Jackson 作为默认设置运行良好。
【问题讨论】:
标签: javascript java node.js spring spring-boot