dva使用cors代理解决前后台数据交互
程序员文章站
2024-03-24 15:00:28
...
(dva使用cors代理解决前后台数据交互&)
dva使用cors代理解决前后台数据交互&
首先要修改.roadhogrc文件
"proxy": {
"/api": {
"target": "http://localhost:1111/",
"changeOrigin": true,
"pathRewrite": { "^/api" : "" }
}
},
然后设置dva的request文件,设置defaultOptions={mode:’cors’}属性,其他原封不动保留。
request.js
import fetch from 'dva/fetch';
function parseJSON(response) {
return response.json();
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(response.statusText);
error.response = response;
throw error;
}
/**
* Requests a URL, returning a promise.
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
export default function request(url, options) {
const defaultOptions = {
mode: 'cors',
};
const mergeOptions = {
...options,
...defaultOptions
};
return fetch(url, mergeOptions)
.then(checkStatus)
.then(parseJSON)
.then((data) => ({ data }))
.catch((err) => ({ err }));
}
java后台改动的地方,需要设置cors来处理复杂请求。
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {
@Bean
public RemoteIpFilter remoteIpFilter(){
return new RemoteIpFilter();
}
@Bean
public CorsFilter corsFilter(){
// SpringMvc 提供了 CorsFilter 过滤器
// 初始化cors配置对象
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许跨域的域名,如果要携带cookie,不要写*,*:代表所有域名都可以跨域访问
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true); // 设置允许携带cookie
corsConfiguration.addAllowedMethod("*"); // 代表所有的请求方法:GET POST PUT DELETE...
corsConfiguration.addAllowedHeader("*"); // 允许携带任何头信息
//初始化cors配置源对象
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
// 返回corsFilter实例,参数:cors配置源对象
return new CorsFilter(corsConfigurationSource);
}
@Bean
public FilterRegistrationBean testFilterRegistration(){
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
registration.addUrlPatterns("/*");
registration.addInitParameter("paramName","paramValue");
registration.setName("MyFilter");
registration.setOrder(1);
return registration;
}
public class MyFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) servletResponse;
HttpServletRequest req = (HttpServletRequest) servletRequest;
String origin = req.getHeader("Origin");
if (!org.springframework.util.StringUtils.isEmpty(origin)) {
//带cookie的时候,origin必须是全匹配,不能使用*
res.addHeader("Access-Control-Allow-Origin", origin);
}
res.addHeader("Access-Control-Allow-Methods", "*");
String headers = req.getHeader("Access-Control-Request-Headers");
// 支持所有自定义头
if (!org.springframework.util.StringUtils.isEmpty(headers)) {
res.addHeader("Access-Control-Allow-Headers", headers);
}
res.addHeader("Access-Control-Max-Age", "3600");
// enable cookie
res.addHeader("Access-Control-Allow-Credentials", "true");
filterChain.doFilter(req, res);
}
@Override
public void destroy() {
Map map = new HashMap();
}
}
}
基本就可以实现代理服务了
测试代理跳转功能,设置服务地址
通过fetch实现代理路径跳转
import request from '../utils/request';
import qs from 'qs';
import {url} from '../utils/commonConstant';
export async function query(params) {
console.log(params);
if(JSON.stringify(params) == "{}"){
return request(`${url}/users/query`);
}
return request(`${url}/users/query?${qs.stringify(params)}`);
}
export async function create(params) {
console.log(params);
return request(`${url}/users/create`, {
method: 'post',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(params),
});
}
export async function remove(params) {
console.log(params);
return request(`${url}/users/delete/${params.id}`, {
method: 'delete',
body: qs.stringify(params),
});
}
export async function update(params) {
return request(`${url}/users/update`, {
method: 'put',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(params),
});
}
即可访问后台数据
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.szewec.model.vo.PageBean;
import com.szewec.model.vo.Puser;
import com.szewec.service.PuserService;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@RestController
@EnableSwagger2
@Api("swaggerDemoController相关的api")
@RequestMapping("/api")
public class PuserController {
@Resource
private PuserService puserService;
@RequestMapping("/users/test")
public PageBean<Puser> getParamsTest(HttpServletRequest request, HttpServletResponse response) throws IOException {
String field = request.getParameter("field");
String keyword = request.getParameter("keyword");
ObjectMapper mapper = new ObjectMapper();
String s = "{\"total\":3,\"current\":1,\"list\":[{\"id\":1,\"name\":\"张三\",\"age\":23,\"sex\":\"女\",\"address\":\"成都\"},{\"id\":2,\"name\":\"李四\",\"age\":24,\"sex\":\"男\",\"address\":\"杭州\"},{\"id\":3,\"name\":\"王五\",\"age\":25,\"sex\":\"男\",\"address\":\"上海\"}]}";
if(StringUtils.isNotBlank(field)){
s = "{\"total\":3,\"current\":1,\"list\":[{\"id\":1,\"name\":\"张三111111\",\"age\":23,\"sex\":\"女\",\"address\":\"成都\"},{\"id\":2,\"name\":\"李四\",\"age\":24,\"sex\":\"男\",\"address\":\"杭州\"},{\"id\":3,\"name\":\"王五\",\"age\":25,\"sex\":\"男\",\"address\":\"上海\"}]}";
}
return mapper.readValue(s,new TypeReference<PageBean<Puser>>(){});
}
@RequestMapping("/users/query")
public PageBean<Puser> usersFuzzyQuery(HttpServletRequest request, HttpServletResponse response) throws IOException {
Puser puser = new Puser();
String field = request.getParameter("field");
String keyword = request.getParameter("keyword");
String current = request.getParameter("current");
if(null==current){
current="0";
}
if(StringUtils.isNotBlank(field)&&StringUtils.isNotBlank(keyword)){
if("name".equals(field)){
puser.setName(keyword);
}
if("address".equals(field)){
puser.setAddress(keyword);
}
}
List<Puser> usersList = puserService.usersFuzzyQuery(puser,Integer.valueOf(current));
PageBean<Puser> pageBean = new PageBean<Puser>(usersList.size(),Integer.valueOf(current),10);
pageBean.setList(usersList);
return pageBean;
}
@RequestMapping("/users/create")
public PageBean<Puser> createPuser(@RequestBody Puser puser) throws IOException {
int fid = (int)((Math.random()*9+1)*100000);
puser.setId(fid);
puserService.addUsers(puser);
PageBean<Puser> pageBean = new PageBean<Puser>();
List<Puser> usersList = puserService.usersFuzzyQuery(new Puser(),0);
pageBean.setCurrent(1);
pageBean.setTotal(3);
pageBean.setList(usersList);
return pageBean;
}
@RequestMapping("/users/update")
public Integer updatePuser(@RequestBody Puser puser) throws IOException {
System.out.println(puser);
Integer updateRows = puserService.updateUser(puser);
return updateRows;
}
@RequestMapping("/users/delete/{id}")
public Integer deletePuser(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Integer id) throws IOException {
System.out.println(id);
Integer deleteRows = puserService.deleteUser(id);
return deleteRows;
}
}
推荐阅读