后台工程的搭建
解决跨域问题(通过增加filter)
跨域请求错误
问题描述:Failed to load http://localhost:8099/api/user/insertUser: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8099' is therefore not allowed access.
解决方式
因为浏览器的同源策略,所谓的同源是指,域名,协议,端口相同。
因此产生了跨域问题,解决方式如下:
package com.lys.k8s.filter;/**
* Created by lys on 2019/1/30.
*/
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @ClassName CasSecurityFilter
* @Description TODO
* @Author 刘云生
* @Date 2019/1/30 11:01
**/
@Component
public class CasSecurityFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
// 说明:httpResponse.addHeader("Access-Control-Allow-Origin","http://127.0.0.1:8020")添加的响应的地址;
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
集成springfox-swagger-ui 实现接口的可视化
pom.xml增加依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
Controller层实现例子
package com.lys.k8s.controller;
import com.lys.k8s.entity.dto.ResultDTO;
import com.lys.k8s.entity.User;
import com.lys.k8s.entity.dto.UserDTO;
import com.lys.k8s.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
* @ClassName UserController
* @Description 用户
* @Author liuysh
* @Date 2019/1/24 11:06
**/
@Controller
@RequestMapping(value = "api/user")
@Api(value = "用户的增删改查")
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value = "selectByPrimaryKey", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "根据id获取用户信息")
public ResponseEntity<Object> selectByPrimaryKey(@RequestParam String userId) {
ResultDTO resultDTO = new ResultDTO();
try{
resultDTO.setFlag(true);
resultDTO.setResultData(userService.selectByPrimaryKey(userId));
}catch (Exception e){
resultDTO.setFlag(false);
resultDTO.setMessage("获取失败");
}
return new ResponseEntity<>(resultDTO, HttpStatus.OK);
}
@RequestMapping(value = "deleteByPrimaryKey", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "根据id删除用户")
public ResponseEntity<Object> deleteByPrimaryKey(@RequestParam String userId) {
ResultDTO resultDTO = new ResultDTO();
try{
resultDTO.setFlag(true);
resultDTO.setResultData(userService.deleteByPrimaryKey(userId));
}catch (Exception e){
resultDTO.setFlag(false);
resultDTO.setMessage("获取失败");
}
return new ResponseEntity<>(resultDTO, HttpStatus.OK);
}
@RequestMapping(value = "/insertUser")
@ResponseBody
@ApiModelProperty(value="user",notes = "修改后用户信息的json串")
@ApiOperation(value = "新增用户", notes="返回新增的用户信息")
public ResponseEntity<Object> insertUser(@RequestBody User user) {
ResultDTO resultDTO = new ResultDTO();
try{
resultDTO.setFlag(true);
resultDTO.setResultData(userService.insert(user));
}catch (Exception e){
resultDTO.setFlag(false);
resultDTO.setMessage("插入失败");
}
return new ResponseEntity<>(resultDTO, HttpStatus.OK);
}
}
数据库表结构
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`user_id` varchar(36) COLLATE utf8_unicode_ci NOT NULL,
`user_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`user_password` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
antd 平台的搭建
下载安装antd pro项目
$ git clone https://github.com/ant-design/ant-design-pro.git --depth=1
$ cd ant-design-pro
$ npm install
$ npm start # visit http://localhost:8000
设置接口调用代理
# 后台接口为 http://localhost:8099/api/user/insertUser
# 修改config/config.js的下面代码
proxy: {
'/api': {
target: 'http://10.6.6.193:8099/',
changeOrigin: false,
pathRewrite: { '^/api': '/api' },
},
},
前端调用样例
在显示页面中(1.利用封装框架调用--推荐)
// D:\lys_spaces_web\ant-design-pro\src\pages\UserManagement\models\usermanagement.js
const { dispatch } = this.props;
let user={};
user.userId='localhost';
user.userName='99999';
user.userPassword='999';
dispatch({
type: 'usermanagement/insertUserEffects',
payload: user
});
在显示页面中(2.直接调用)
let url = 'http://10.6.6.193:8099/api/user/insertUser';
console.log(JSON.stringify(user));
console.log(user);
var fetchOption = {
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', },
body:JSON.stringify(user)
}
// 开始所需数据的下载
fetch(url,fetchOption)
.then(response=>response.json())
.then(responseJson=>{
console.log(responseJson);
}).catch(function(e) {
console.log("Oops, error");
});
调用 model 的 effect
import { insertUser} from "../../../services/api";
export default {
namespace: 'usermanagement',
state: {
list: [],
currentUser: {},
},
effects: {
*insertUserEffects({ payload }, { call, put }) {
const response = yield call(insertUser, payload);
yield put({
type: 'save',
payload: response,
});
},
},
reducers: {
save(state, action) {
return {
...state,
list: action.payload,
};
},
},
};
调用统一管理的 service 请求函数
// D:\lys_spaces_web\ant-design-pro\src\services\api.js
import { stringify } from 'qs';
import request from '@/utils/request';
export async function insertUser(params) {
debugger
return request('/api/user/insertUser', {
method: 'POST',
body: params,
});
}
使用封装的 request.js 发送请求;
总结
在 Ant Design Pro 中,一个完整的前端 UI 交互到服务端处理流程是这样的:
1.UI 组件交互操作;
2.调用 model 的 effect;
3.调用统一管理的 service 请求函数;
4.使用封装的 request.js 发送请求;
5.获取服务端返回;
6.然后调用 reducer 改变 state;
7.更新 model。