【发布时间】:2016-11-28 17:47:31
【问题描述】:
我使用 Java Spring Cloud / Boot 构建了一个 REST API 服务。首先,我创建了一个连接到 MongoDB 的简单类和一个带有服务的控制器,该服务应该允许我添加、删除、更新和获取所有对象。使用 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 中的控制器代码:
@RequestMapping(method = RequestMethod.POST, path = "/add")
public void addAsset(@RequestBody Asset asset) {
assetService.addAsset(asset);
}
在邮递员中进行时状态正常:
我在使用 Redux / Fetch API 时遇到的错误(我只删除了目录结构,因为其中包含公司名称):
已经坚持了一段时间,非常感谢任何帮助!
编辑资产对象:
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;
}
}
【问题讨论】:
-
你能复制/粘贴你的资产 java 对象吗?
-
你的 json 中缺少 ID,因此得到 400。你能告诉我结果吗?
-
不,没关系,如果我不提供 id,mongoDB 只会创建一个。
-
对我来说,Spring 似乎拒绝了您的请求,因为它无法将您的 json 放入您的对象中,因为您没有在 json 中提供任何 ID 字段
-
不确定 fetch API 的工作原理。您是否尝试将正文格式化为 json?正文:JSON.stringify(assetObject)?
标签: java spring rest fetch-api