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里的地址
- ? ? ? }
- ? ? })
- ? );
- };
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。