網站首頁 編程語言 正文
react axios結合后端實現GET和POST請求
區別在這里不做介紹了,POST方法比GET方法稍微安全一點,GET方法比POST方法要快一些,個人感覺傳遞單個參數用GET,傳遞多個參數用POST。
get實現方式1(參數直接在url中)
- 前端
export function getAllSubstationsByUser() {
? return axios.get(`/api/integratedEnergy/all/${user}/substations`);
}
- 后端
? ?@RequestMapping(value = "/all/{user}/all/substations", method = RequestMethod.GET)
? ? public ?ResponseEntity<List<Map<String, Object>>> getAllSubstationsByUserAreas(@PathVariable("user") String user) {
? ? String a = user;
? ? // todo 實現方法
}
get時間方式2(作為JSONString跟在url末尾)
- 前端
? const params = {
? ? ? user: 'admin',
? ? };
? ??
export function getAllSubstationsByUser(params) {
? return axios.get(`/api/integratedEnergy/all/substations`, { params });
}
- 后端
? ? @RequestMapping(value = "/all/substations", method = RequestMethod.GET)
? ? public ResponseEntity<List<Map<String, Object>>> getAllSubstationsByUserAreas(@RequestParam(value = "user", defaultValue = "") String user) {
? ? ? ? List<Map<String, Object>> mapList = new ArrayList<>();
? ? ? ? String a = user;
? ? ? ? // todo 實現方法
? ? ? ? return new ResponseEntity<>(mapList, HttpStatus.OK);
? ? }
post實現(傳遞JSONObject)
- 前端
const params = { id: 'admin', name: '用戶' }
export function getChildrenDevicesByParent(params) {
? return axios.post(`/api/integratedEnergy/all/child/devices`, params);
}
- 后端
? ?@RequestMapping(value = "/all/child/devices", method = RequestMethod.POST)
? ? public ResponseEntity<List<Map<String, Object>>> getStorageHistoryData(@RequestBody JSONObject params) {
? ? List<Map<String, Object>> mapList = new ArrayList<>();
?? ?String id = params.getString("id").trim());
?? ?String name = params.getString("name").trim());
?? ?// todo 實現方法
? ? return new ResponseEntity<>(mapList, HttpStatus.OK);
? ? }
react?項目axios請求配置
axios請求封裝
1、安裝 npm I axios
2、首先在根目錄下建立server.js文件內容如下
import axios from 'axios'
axios.defaults.baseURL = '' ?//根據項目自己更改
//一些配置,發起請求和響應可以打印出來查看
axios.interceptors.request.use((config)=>{
? ? //這里是用戶登錄的時候,將token寫入了sessionStorage中了,之后進行其他的接口操作時,進行身份驗證。
? ? config.headers.token = localStorage.getItem("cookie");
? ? return config;
})
//在response中
axios.interceptors.response.use(config =>{
? ? return config;
})
const http = {
? ? post:'',
? ? get:'',
? ? getParams:''
}
http.post = function (api, data){ ?// post請求
? ? return new Promise((resolve, reject)=>{
? ? ? ? axios.post(api,data).then(response=>{
? ? ? ? ? ? resolve(response)
? ? ? ? })
? ? })
}
http.get = function (api, data){ // get請求
? ? return new Promise((resolve, reject)=>{
? ? ? ? axios.get(api,data).then(response=>{
? ? ? ? ? ? resolve(response)
? ? ? ? })
? ? })
}
http.getParams = function (api, param){ //get請求 需要傳參
? ? return new Promise((resolve, reject)=>{
? ? ? ? axios.get(api, {params: param}).then(response => {
? ? ? ? ? ? resolve(response.data)
? ? ? ? }, err => {
? ? ? ? ? ? reject(err)
? ? ? ? }).catch((error) => {
? ? ? ? ? ? reject(error)
? ? ? ? })
? ? })
}
export default http
3、組件中使用
import http from '../../server'; ?// 首先引入server文件
http.get('api/接口名稱').then(res => {
? ? ? ?console.log(res)
}).catch(error => {
? ? ? ?console.error(error)
})
這個時候請求接口我們回遇到跨域的問題,接下來告訴你們如何解決跨域
1、在根目錄下建立setupProxy.js文件內容如下
const proxy = require('http-proxy-middleware');
module.exports = function(app) {
? app.use(
? ? '/api',
? ? proxy.createProxyMiddleware({
? ? ? target: 'http://172.21.211.132:8000', // 后臺服務地址以及端口號
? ? ? changeOrigin: true, // 是否跨域
? ? ? pathRewrite: {
? ? ? ? '^/api': '' // 路徑重寫,用/api代替target里的地址
? ? ? }
? ? })
? );
};
總結
原文鏈接:https://blog.csdn.net/qq_34307801/article/details/105046975
相關推薦
- 2022-01-21 Flink中window 窗口和時間以及watermark水印
- 2022-04-12 原生drag拖拽后元素過大,擋住其他可拖動位置無法拖動問題
- 2023-09-18 element-plus 字體變色之cell-style
- 2022-04-05 debian:根據文件名稱,找到對應的包
- 2022-06-17 docker修改容器配置文件的3種方法總結_docker
- 2023-12-15 Linux系統中date命令、hwclock命令 語法詳解
- 2022-08-31 ES6變量賦值和基本數據類型詳解_基礎知識
- 2024-07-13 Springboot使用注解實現權限校驗
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支