经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » React » 查看文章
react中axios结合后端实现GET和POST请求方式
来源:jb51  时间:2023/2/15 9:19:29  对本文有异议

react axios结合后端实现GET和POST请求

区别在这里不做介绍了,POST方法比GET方法稍微安全一点,GET方法比POST方法要快一些,个人感觉传递单个参数用GET,传递多个参数用POST。

get实现方式1(参数直接在url中)

  • 前端
  1. export function getAllSubstationsByUser() {
  2. ? return axios.get(`/api/integratedEnergy/all/${user}/substations`);
  3. }
  • 后端
  1. ? ?@RequestMapping(value = "/all/{user}/all/substations", method = RequestMethod.GET)
  2. ? ? public ?ResponseEntity<List<Map<String, Object>>> getAllSubstationsByUserAreas(@PathVariable("user") String user) {
  3. ? ? String a = user;
  4. ? ? // todo 实现方法
  5. }

get时间方式2(作为JSONString跟在url末尾)

  • 前端
  1. ? const params = {
  2. ? ? ? user: 'admin',
  3. ? ? };
  4. ? ??
  5. export function getAllSubstationsByUser(params) {
  6. ? return axios.get(`/api/integratedEnergy/all/substations`, { params });
  7. }
  • 后端
  1. ? ? @RequestMapping(value = "/all/substations", method = RequestMethod.GET)
  2. ? ? public ResponseEntity<List<Map<String, Object>>> getAllSubstationsByUserAreas(@RequestParam(value = "user", defaultValue = "") String user) {
  3. ? ? ? ? List<Map<String, Object>> mapList = new ArrayList<>();
  4. ? ? ? ? String a = user;
  5. ? ? ? ? // todo 实现方法
  6. ? ? ? ? return new ResponseEntity<>(mapList, HttpStatus.OK);
  7. ? ? }

post实现(传递JSONObject)

  • 前端
  1. const params = { id: 'admin', name: '用户' }
  2.  
  3. export function getChildrenDevicesByParent(params) {
  4. ? return axios.post(`/api/integratedEnergy/all/child/devices`, params);
  5. }
  • 后端
  1. ? ?@RequestMapping(value = "/all/child/devices", method = RequestMethod.POST)
  2. ? ? public ResponseEntity<List<Map<String, Object>>> getStorageHistoryData(@RequestBody JSONObject params) {
  3. ? ? List<Map<String, Object>> mapList = new ArrayList<>();
  4. ?? ?String id = params.getString("id").trim());
  5. ?? ?String name = params.getString("name").trim());
  6. ?? ?// todo 实现方法
  7.  
  8. ? ? return new ResponseEntity<>(mapList, HttpStatus.OK);
  9. ? ? }

react 项目axios请求配置

axios请求封装

1、安装 npm I axios

2、首先在根目录下建立server.js文件内容如下

  1. import axios from 'axios'
  2. axios.defaults.baseURL = '' ?//根据项目自己更改
  3. //一些配置,发起请求和响应可以打印出来查看
  4. axios.interceptors.request.use((config)=>{
  5. ? ? //这里是用户登录的时候,将token写入了sessionStorage中了,之后进行其他的接口操作时,进行身份验证。
  6. ? ? config.headers.token = localStorage.getItem("cookie");
  7. ? ? return config;
  8. })
  9. //在response中
  10. axios.interceptors.response.use(config =>{
  11. ? ? return config;
  12. })
  13. const http = {
  14. ? ? post:'',
  15. ? ? get:'',
  16. ? ? getParams:''
  17. }
  1. http.post = function (api, data){ ?// post请求
  2. ? ? return new Promise((resolve, reject)=>{
  3. ? ? ? ? axios.post(api,data).then(response=>{
  4. ? ? ? ? ? ? resolve(response)
  5. ? ? ? ? })
  6. ? ? })
  7. }
  8. http.get = function (api, data){ // get请求
  9. ? ? return new Promise((resolve, reject)=>{
  10. ? ? ? ? axios.get(api,data).then(response=>{
  11. ? ? ? ? ? ? resolve(response)
  12. ? ? ? ? })
  13. ? ? })
  14. }
  15. http.getParams = function (api, param){ //get请求 需要传参
  16. ? ? return new Promise((resolve, reject)=>{
  17. ? ? ? ? axios.get(api, {params: param}).then(response => {
  18. ? ? ? ? ? ? resolve(response.data)
  19. ? ? ? ? }, err => {
  20. ? ? ? ? ? ? reject(err)
  21. ? ? ? ? }).catch((error) => {
  22. ? ? ? ? ? ? reject(error)
  23. ? ? ? ? })
  24. ? ? })
  25. }
  26.  
  27. export default http

3、组件中使用

  1. import http from '../../server'; ?// 首先引入server文件
  2.  
  3. http.get('api/接口名称').then(res => {
  4. ? ? ? ?console.log(res)
  5. }).catch(error => {
  6. ? ? ? ?console.error(error)
  7. })

这个时候请求接口我们回遇到跨域的问题,接下来告诉你们如何解决跨域

1、在根目录下建立setupProxy.js文件内容如下

  1. const proxy = require('http-proxy-middleware');
  2. module.exports = function(app) {
  3. ? app.use(
  4. ? ? '/api',
  5. ? ? proxy.createProxyMiddleware({
  6. ? ? ? target: 'http://172.21.211.132:8000', // 后台服务地址以及端口号
  7. ? ? ? changeOrigin: true, // 是否跨域
  8. ? ? ? pathRewrite: {
  9. ? ? ? ? '^/api': '' // 路径重写,用/api代替target里的地址
  10. ? ? ? }
  11. ? ? })
  12. ? );
  13. };

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号