为什么Spring返回一个空列表给我?

huangapple go评论109阅读模式
英文:

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(&quot;http://localhost:8080/addSuspect&quot;, {
&quot;method&quot;: &quot;POST&quot;,
&quot;headers&quot;: {
&quot;content-type&quot;: &quot;application/json&quot;
},
&quot;body&quot;: item
})
.then(response =&gt; {
console.log(response);
})
.catch(err =&gt; {
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:&quot;You need to upload at least 2 files!&quot;})
return
}
//Check if the file is the correct file
console.log(&quot;Files:&quot;)
for (var i=0, l=event.target.files.length; i&lt;l; i++) {
console.log(event.target.files[i].name);
if (event.target.files[i].name.includes(&quot;_suspected&quot;)){
file = event.target.files[i]
}
else if (event.target.files[i].name.includes(&quot;_movements&quot;)){
file2 = event.target.files[i]
}
else{
this.setState({error:true, errorMsg:&quot;You have uploaded invalid files! Please rename the files to &lt;filename&gt;_suspected (For suspected cases) or &lt;filename&gt;_movement (For suspected case movement)&quot;})
return
}
}
//Reads the first file (Suspected profile)
if (file) {
const reader = new FileReader();
reader.onload = () =&gt; {
// Use reader.result
const lols = Papa.parse(reader.result, {header: true, skipEmptyLines: true}, )
console.log(lols.data)
// Posting csv data into db
// this.postData(&#39;&quot;&#39; + JSON.stringify(lols.data) + &#39;&quot;&#39;)
this.postData(JSON.stringify(lols.data))
// Adds names into dropdown
this.setState({dataList: [&quot;None&quot;, ...lols.data.map(names =&gt; names.firstName + &quot; &quot; + 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(&quot;/listAllPeopleProfiles&quot;)
//Removes the CORS error
@CrossOrigin(origins = &quot;http://localhost:3000&quot;)
private Iterable&lt;Peopleprofile&gt; getAllPeopleProfiles (){
return profileMapper.findAllPeopleProfile();
}
@GetMapping(&quot;/listAllSuspectedCases&quot;)
@CrossOrigin(origins = &quot;http://localhost:3000&quot;)
private Iterable&lt;Suspected&gt; getAllSuspected(){
return suspectedMapper.findallSuspected();
}
@PostMapping(&quot;/addSuspect&quot;)
@CrossOrigin(origins = &quot;http://localhost:3000&quot;)
private void newSuspectedcases(ArrayList&lt;Suspected&gt; unformattedcases){
//        try {
//            final JSONObject obj = new JSONObject(unformattedcases);
//
//            System.out.println(obj);
////            ObjectMapper mapper = new ObjectMapper();
////            List&lt;Suspected&gt; value = mapper.writeValue(obj, Suspected.class);
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
//        Gson gson = new Gson();
//        List&lt;Suspected&gt; suspectedCases = gson.fromJson(unformattedcases, new TypeToken&lt;List&lt;Suspected&gt;&gt;(){}.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(&quot;/addSuspect&quot;)
@CrossOrigin(origins = &quot;http://localhost:3000&quot;)
@ResponseBody
private ArrayList&lt;Suspected&gt; newSuspectedcases(@RequestBody ArrayList&lt;Suspected&gt; 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&lt;Suspected&gt; 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&lt;Suspected&gt; instead of ArrayList&lt;Suspected&gt;

So the final method should look like this:

   @PostMapping(&quot;/addSuspect&quot;)
@CrossOrigin(origins = &quot;http://localhost:3000&quot;)
private List&lt;Suspected&gt; newSuspectedcases(@RequestBody List&lt;Suspected&gt; 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.

huangapple
  • 本文由 发表于 2020年7月30日 00:44:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63158499.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定