一、前端vue项目
在项目中创建request.js文件,添加以下内容
import axios from "axios";
const api = axios.create({ //这里配置的是后端服务提供的接口baseURL: "http://localhost:8080/web-demo",timeout: 1000}
);
export default api;
在main.js中添加
import {createApp} from 'vue'
import App from './App.vue'
import router from './route/index' // 导入路由器
import axios from './request' //引入request.js// 超时时间是5秒
axios.defaults.timeout = 5000;
// 当前请求为跨域类型时是否在请求中协带cookie
axios.defaults.withCredentials = truelet app=createApp(App)
app.use(router) // 使用路由
app.provide("$axios", axios);
app.mount('#app')
//配置axios的全局引用
app.config.globalProperties.$axios = axios;
xxx.vue中使用方式:
api({url: "/book/delBook", // 服务端地址method: "post", // 请求方式params: {"ids": ids} // 携带参数}).then((res) => { // 成功触发函数res.data // 服务端返回的json数据 });
二、Servlet项目解决跨域请求问题
使用过滤器对响应头进行设置
package com.buba.filter;import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** @author 杨柳* @title MyFilter 对跨域请求进行设置* @date 2023/11/28 14:32*/
@WebFilter("/*")
public class MyFilter implements Filter {@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;HttpServletResponse resp = (HttpServletResponse) response;// 当前端携带cookie时,这里的值不能设置成*resp.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");resp.setHeader("Access-Control-Max-Age", "3600");resp.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type");resp.setHeader("Access-Control-Allow-Credentials", "true");chain.doFilter(request, response);}
}