我尝试使用Axios向我的应用程序接口发出post请求,但是尽管添加了@ResponseBody注释,但JSON并没有被正确地反序列化为java对象。该对象的字段仅为null。
这是我的控制器:
@RestController
class WordSearchController {
private long count;
@CrossOrigin(origins = "http://localhost:3000")
@PostMapping(
value = "/word",
consumes = {MediaType.APPLICATION_JSON_VALUE}
)
public long Search (@RequestBody WordSearch wordsearch) {
count = wordsearch.search();
return count;
}
}下面是我在handleSubmit中的axios.post调用:
class SubmitForm extends Component {
state = {
sentence: '',
word: '',
};
handleSubmit = event => {
event.preventDefault();
console.log(this.state.sentence);
const user = {
sentence: this.state.sentence,
word: this.state.word,
}
console.log(user)
axios.post('http://localhost:8080/word', {user})
.then(res=>{
console.log(res);
console.log(res);
})
}下面是WordSearch.java:
public class WordSearch {
@JsonProperty("sentence")
private String sentence;
@JsonProperty("word")
private String word;
public void setSentence(String sentence) {
this.sentence = sentence;
}
public void setWord(String word) {
this.word = word;
}
public String getSentence() {
return this.sentence;
}
public String getWord() {
return this.word;
}
public long search() {
Pattern word_pattern = Pattern.compile("\\b" + (this.word) + "\\b");
Matcher countWord = word_pattern.matcher(this.sentence);
long count = countWord.results().count();
/* int count = 0;
String [] words = (this.sentence).split(" ");
for (int i = 0; i < words.length; i++) {
if ((words[i]).equals(this.word)) {
count++;
}
}
*/
return count;
}}
有效负载显示为{sentence: "hello", word: "world"}
发布于 2021-03-10 15:39:11
axios.post('http://localhost:8080/word', user):axios.post('http://localhost:8080/word', {user})应该是这样的吗?
看起来user对象被包装到另一个对象中。
此外,您还可以使用postman进行测试,以查看问题出在客户端还是服务器端。
https://stackoverflow.com/questions/66559122
复制相似问题