日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

react中axios結合后端實現GET和POST請求方式_React

作者:成續源 ? 更新時間: 2023-05-06 編程語言

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

欄目分類
最近更新