gpt4 book ai didi

javascript - 如何使用 reactjs 向服务器发送请求?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:06:45 25 4
gpt4 key购买 nike

我有一个用 jquery 和 spring mvc 开发的 web 应用程序...一切都运行良好...但现在我想在我的应用程序中使用 React JS...我想在 react js 中创建一个表单并且将 ajax 请求发送到我的 spring mvc Controller ...我知道如何使用 jquery 但不知道如何使用 react js...请告诉我一种创建表单并将请求发送到 spring mvc Controller 的方法....这是我想要获取请求的 Controller 方法...

@RequestMapping(value = "/saveuser", method = RequestMethod.POST)
public @ResponseBody String Save(/*@Valid Users user, BindingResult result,*/HttpServletRequest request, Model model,
@RequestParam(required = false) Boolean reverseBeforeSave) {

String userName = request.getParameter("username");
String password = request.getParameter("password");
String firstName = request.getParameter("first_name");
String lastName = request.getParameter("last_name");
System.out.println("save method");
String[] roleNames = request.getParameterValues("roles");

userService.saveUserandRoles(userName, password, firstName, lastName, roleNames);
return "success";

}

我在 StackOverflow 中查看了不同的解决方案,并在谷歌上进行了搜索,但没有得到任何正确的结果。

最佳答案

安装axios

$ npm install axios

导入axios

import axios from 'axios';

示例 GET 请求

axios.get('https://api.example.com/')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

示例 POST 请求

var body = {
firstName: 'testName',
lastName: 'testLastName'
};

axios.post('https://api.example.com/', body)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

关于javascript - 如何使用 reactjs 向服务器发送请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49377363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com