英文:
Why is spring returning me an empty llist?
问题
以下是您的代码的中文翻译部分:
我似乎不知道为什么Spring返回了一个空列表,尽管我已经传递了一个来自ReactJS的JSON.stringify()字符串。
这是我的ReactJS代码:
postData(item){
console.log(item)
fetch("http://localhost:8080/addSuspect", {
"method": "POST",
"headers": {
"content-type": "application/json"
},
"body": item
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
}
uploadFile(event) {
let file
let file2
//检查是否上传了运动和可疑病例档案
if(event.target.files.length !== 2){
this.setState({error:true, errorMsg:"您需要至少上传2个文件!"})
return
}
//检查文件是否正确
console.log("文件:")
for (var i=0, l=event.target.files.length; i<l; i++) {
console.log(event.target.files[i].name);
if (event.target.files[i].name.includes("_suspected")){
file = event.target.files[i]
}
else if (event.target.files[i].name.includes("_movements")){
file2 = event.target.files[i]
}
else{
this.setState({error:true, errorMsg:"您上传了无效的文件!请将文件重命名为<filename>_suspected(用于疑似病例)或<filename>_movement(用于疑似病例移动)"})
return
}
}
//读取第一个文件(疑似档案)
if (file) {
const reader = new FileReader();
reader.onload = () => {
// 使用 reader.result
const lols = Papa.parse(reader.result, {header: true, skipEmptyLines: true}, )
console.log(lols.data)
// 将CSV数据发布到数据库
// this.postData('"' + JSON.stringify(lols.data) + '"')
this.postData(JSON.stringify(lols.data))
// 将名称添加到下拉列表
this.setState({dataList: ["None", ...lols.data.map(names => names.firstName + " " + names.lastName)]})
const data = lols.data
this.setState({suspectCases: data})
}
reader.readAsText(file)
}
}
这是从console.log()中获取的内容:
[{"id":"5","firstName":"Bernadene","lastName":"Earey","email":"bearey4@huffingtonpost.com","gender":"Female","homeLongtitude":"","homeLatitude":"","homeShortaddress":"","homePostalcode":"552209","maritalStatus":"M","phoneNumber":"92568768","company":"Yadel","companyLongtitude":"","companyLatitude":""},{"id":"14","firstName":"Mada","lastName":"Lafaye","email":"mlafayed@gravatar.com","gender":"Female","homeLongtitude":"","homeLatitude":"","homeShortaddress":"","homePostalcode":"447136","maritalStatus":"M","phoneNumber":"85769345","company":"Eare","companyLongtitude":"","companyLatitude":""}]
以下是我的Spring控制器中的代码:
@RestController
public class HomeController {
private final profileMapper profileMapper;
private final suspectedMapper suspectedMapper;
public HomeController(@Autowired profileMapper profileMapper, @Autowired suspectedMapper suspectedMapper) {
this.profileMapper = profileMapper;
this.suspectedMapper = suspectedMapper;
}
@GetMapping("/listAllPeopleProfiles")
//移除CORS错误
@CrossOrigin(origins = "http://localhost:3000")
private Iterable<Peopleprofile> getAllPeopleProfiles (){
return profileMapper.findAllPeopleProfile();
}
@GetMapping("/listAllSuspectedCases")
@CrossOrigin(origins = "http://localhost:3000")
private Iterable<Suspected> getAllSuspected(){
return suspectedMapper.findallSuspected();
}
@PostMapping("/addSuspect")
@CrossOrigin(origins = "http://localhost:3000")
private void newSuspectedcases(ArrayList<Suspected> unformattedcases){
System.out.println(unformattedcases);
}
}
英文:
I dont seem to know why Spring is returning me an empty list enough I have passed in a JSON.stringify() string from reactJS
This is my code for reactJS
postData(item){
console.log(item)
fetch("http://localhost:8080/addSuspect", {
"method": "POST",
"headers": {
"content-type": "application/json"
},
"body": item
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
}
uploadFile(event) {
let file
let file2
//Check if the movements andsuspected case profiles are uploaded
if(event.target.files.length !== 2){
this.setState({error:true, errorMsg:"You need to upload at least 2 files!"})
return
}
//Check if the file is the correct file
console.log("Files:")
for (var i=0, l=event.target.files.length; i<l; i++) {
console.log(event.target.files[i].name);
if (event.target.files[i].name.includes("_suspected")){
file = event.target.files[i]
}
else if (event.target.files[i].name.includes("_movements")){
file2 = event.target.files[i]
}
else{
this.setState({error:true, errorMsg:"You have uploaded invalid files! Please rename the files to <filename>_suspected (For suspected cases) or <filename>_movement (For suspected case movement)"})
return
}
}
//Reads the first file (Suspected profile)
if (file) {
const reader = new FileReader();
reader.onload = () => {
// Use reader.result
const lols = Papa.parse(reader.result, {header: true, skipEmptyLines: true}, )
console.log(lols.data)
// Posting csv data into db
// this.postData('"' + JSON.stringify(lols.data) + '"')
this.postData(JSON.stringify(lols.data))
// Adds names into dropdown
this.setState({dataList: ["None", ...lols.data.map(names => names.firstName + " " + names.lastName)]})
const data = lols.data
this.setState({suspectCases: data})
}
reader.readAsText(file)
}
}
Here is what I get from console.log():
>[{"id":"5","firstName":"Bernadene","lastName":"Earey","email":"bearey4@huffingtonpost.com","gender":"Female","homeLongtitude":"","homeLatitude":"","homeShortaddress":"","homePostalcode":"552209","maritalStatus":"M","phoneNumber":"92568768","company":"Yadel","companyLongtitude":"","companyLatitude":""},{"id":"14","firstName":"Mada","lastName":"Lafaye","email":"mlafayed@gravatar.com","gender":"Female","homeLongtitude":"","homeLatitude":"","homeShortaddress":"","homePostalcode":"447136","maritalStatus":"M","phoneNumber":"85769345","company":"Eare","companyLongtitude":"","companyLatitude":""}]
Below shows the Code in my Spring Controller
@RestController
public class HomeController {
private final profileMapper profileMapper;
private final suspectedMapper suspectedMapper;
public HomeController(@Autowired profileMapper profileMapper, @Autowired suspectedMapper suspectedMapper) {
this.profileMapper = profileMapper;
this.suspectedMapper = suspectedMapper;
}
@GetMapping("/listAllPeopleProfiles")
//Removes the CORS error
@CrossOrigin(origins = "http://localhost:3000")
private Iterable<Peopleprofile> getAllPeopleProfiles (){
return profileMapper.findAllPeopleProfile();
}
@GetMapping("/listAllSuspectedCases")
@CrossOrigin(origins = "http://localhost:3000")
private Iterable<Suspected> getAllSuspected(){
return suspectedMapper.findallSuspected();
}
@PostMapping("/addSuspect")
@CrossOrigin(origins = "http://localhost:3000")
private void newSuspectedcases(ArrayList<Suspected> unformattedcases){
// try {
// final JSONObject obj = new JSONObject(unformattedcases);
//
// System.out.println(obj);
//// ObjectMapper mapper = new ObjectMapper();
//// List<Suspected> value = mapper.writeValue(obj, Suspected.class);
// } catch (JSONException e) {
// e.printStackTrace();
// }
//
// Gson gson = new Gson();
// List<Suspected> suspectedCases = gson.fromJson(unformattedcases, new TypeToken<List<Suspected>>(){}.getType());
System.out.println(unformattedcases);
// for (Suspected suspected : suspectedCases){
// suspectedMapper.addSuspectedCase(suspected);
// }
}
}
答案1
得分: 1
-
我不确定我理解你的问题。这是我对你的意思和你想要发生的事情的最佳猜测:
-
你想让你的控制器接收ArrayList < Suspected > 作为POST请求体
-
你想让你的控制器返回ArrayList < Suspected > 作为POST响应体
如果是这样的话,请尝试这样做:
[...]
@PostMapping("/addSuspect")
@CrossOrigin(origins = "http://localhost:3000")
@ResponseBody
private ArrayList<Suspected> newSuspectedcases(@RequestBody ArrayList<Suspected> unformattedcases){
[...]
System.out.println(unformattedcases);
[...]
return unformattedcases;
}
如果不是你的意思,请提供更多信息。
英文:
I am not sure I understand your issue. This is my best guess about what you meant and what you want to happen :
- You want your controller to receive ArrayList < Suspected > as the POST request body
- You want your controller to return ArrayList < Suspected > as the POST response body
If that's the case, try this :
[...]
@PostMapping("/addSuspect")
@CrossOrigin(origins = "http://localhost:3000")
@ResponseBody
private ArrayList<Suspected> newSuspectedcases(@RequestBody ArrayList<Suspected> unformattedcases){
[...]
System.out.println(unformattedcases);
[...]
return unformattedcases;
}
If it's not what you meant, please provide more information.
答案2
得分: 0
首先,您的控制器方法返回void
,而不是,如果我理解正确的话,您试图发送的有效负载。您必须让您的控制器方法返回List<Suspected>
以接收响应中的请求体。
另一个问题是您在参数上缺少@RequestBody
注解,该注解告诉Spring从请求中获取请求体并尝试将其反序列化为Suspects的ArrayList。
另一点要注意的是,在您的方法中使用接口而不是实现类作为参数和返回值是一种良好的做法。考虑使用List<Suspected>
而不是ArrayList<Suspected>
。
因此,最终的方法应如下所示:
@PostMapping("/addSuspect")
@CrossOrigin(origins = "http://localhost:3000")
private List<Suspected> newSuspectedcases(@RequestBody List<Suspected> unformattedcases){
[...]
System.out.println(unformattedcases);
[...]
return unformattedcases;
}
关于CORS问题,您可能希望使用本地代理设置,如React文档中所述:https://create-react-app.dev/docs/proxying-api-requests-in-development/,并在远程环境中配置CORS,而不添加localhost:3000
。
英文:
Firstly, your controller method is returning void
and not, if I undestand correctly, the payload that you're trying to send. You have to make your controller method return List<Suspected>
to receive a body in the response.
Another issue is that you're missing a @RequestBody
annotation on the param, which tells Spring to get the body from the request and try to deserialize it to a ArrayList of Suspects.
Another thing to note, it is a good practice to use interfaces instead of implementation classes as parameters and return value in your methods. Consider using List<Suspected>
instead of ArrayList<Suspected>
So the final method should look like this:
@PostMapping("/addSuspect")
@CrossOrigin(origins = "http://localhost:3000")
private List<Suspected> newSuspectedcases(@RequestBody List<Suspected> unformattedcases){
[...]
System.out.println(unformattedcases);
[...]
return unformattedcases;
}
PS For CORS issues you may want to using a local proxy setup as described in React docs: https://create-react-app.dev/docs/proxying-api-requests-in-development/ And configure CORS for remote environments, without adding localhost:3000.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论