开发中通常会遇到跨域的情况 ,这时就需要解决这个问题.
- 可以通过后端配置
- 前端通过 vue.config.js 配置
devServer: {
open: true,
host: 'localhost',
port: 8080,
//以上的ip和端口是我们本机的;下面为需要跨域的
proxy: {//配置跨域
'/api': {
target: 'http://******.com',//
ws: true, // websoket
changOrigin: true,//允许跨域
pathRewrite: {
'^/api': ''// vue 在代理的时候 会把 url 中的 api 给去掉
}
}
},
在本地访问 http://localhost:8080/api/daodan/order/list
- 端口 8080 后面的 api 是为了匹配 vue.config.js 里面的跨域规则 如果 url(接口路径) 里面带有 api 那么 vue.config.js 会匹配当前 url (接口路径)去帮我们请求接口.
- 如下代码
let params = {startTime: "",type: 2, state: 0,pageIndex: 1, pageSize: 10}; // 传递的参数
let url = 'http://localhost:8080/api/daodan/order/list'; // 接口路径 当然 如果接口数量巨大 那么最好 把接口封装起来.
/**
*我们请求如上接口并且接口中带有 api 那么 vue.config.js 就会匹配到这个 url
*
*从而帮我们做代理 它就会去访问目标路径 http://******.com/daodan/order/list ;
*
*接口中的 "/api" 被重写为 " "; pathRewrite:{ "/api" :" " };
*
*/
axios.post(url,params).then(res => {
console.log(res);
}) ;