我使用 Java Spring Cloud/Boot 构建了 REST API 服务。首先,我创建了一个连接到 MongoDB 的简单类和一个带有服务的 Controller ,该服务允许我添加、删除、更新和获取所有对象。当使用 POSTMAN 时,这些都可以工作,但是当我想使用 redux 和 fetch API 添加或更新对象时,我收到状态 400 和“错误请求”错误。这似乎与我在正文中发送的 JSON 有关,但它与 POSTMAN 等使用的 JSON 格式完全相同。
我在 Redux 中的操作。为了简单/测试目的,我在顶部添加了一个对象,而不是使用从页面发送的对象。
var assetObject = {
"vendor" : "why dis no work?",
"name": "wtf",
"version": "231",
"category" : "qsd",
"technology" : "whatever"
}
export function addAsset(access_token, asset) {
return dispatch => {
fetch(constants.SERVER_ADDRESS + '/as/asset/add',
{
method: 'POST',
credentials: 'include',
headers: {
'Authorization': 'Bearer' + access_token,
'Content-Type': 'application/json'
},
body: assetObject
})
.then(res => dispatch({
type: constants.ADD_ASSET,
asset
}))
}
}
Java Spring 中的 Controller 代码:
@RequestMapping(method = RequestMethod.POST, path = "/add")
public void addAsset(@RequestBody Asset asset) {
assetService.addAsset(asset);
}
在 postman 中执行此操作时状态正常:
使用 Redux/Fetch API 时遇到的错误(我只删除了目录结构,因为其中有公司名称):
已经被困在这个问题上一段时间了,非常感谢任何帮助!
编辑 Assets 对象:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "assets")
public class Asset {
@Id
private String id;
private String vendor;
private String name;
private String version;
private String category;
private String technology;
public Asset() {
}
public Asset(String id,
String vendor,
String name,
String version,
String category,
String technology) {
this.id = id;
this.vendor = vendor;
this.name = name;
this.version = version;
this.category = category;
this.technology = technology;
}
public String getId() {
return id;
}
public String getVendor() {
return vendor;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public String getCategory() {
return category;
}
public String getTechnology() {
return technology;
}
public void setId(String id) {
this.id = id;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public void setName(String name) {
this.name = name;
}
public void setVersion(String version) {
this.version = version;
}
public void setCategory(String category) {
this.category = category;
}
public void setTechnology(String technology) {
this.technology = technology;
}
}
最佳答案
您的错误消息显示:
; required request body is missing
我认为当您的 Controller
方法时会发生错误
尝试根据传入的请求形成一个对象。
当您发送请求时,您必须设置
与对象相关的每个字段。
如果您打算不设置属性,则应该使用 @JsonIgnore
注释标记该字段。
您可以在变量上使用@JsonIgnore
注释,这将忽略此属性
形成对象时以及输出对象时。
在 setter 方法
上使用 @JsonIgnore
注释,我认为你现在应该这样做,因为
您在发出请求时忽略了 id 属性
。
@JsonIgnore
public void setId(String id) {
this.id = id;
}
并且您可以从 Controller 方法
返回httpstatus
代码,
以便客户端知道请求已成功
@ResponseBody
public ResponseEntity<String> addAsset(@RequestBody Asset asset) {
return new ResponseEntity<String>("your response here", HttpStatus.OK);
}
关于Java Spring REST API 状态 400 对 POST/PUT 的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38566832/