cordova+Vue(cli3)+springboot跨域

  • Post author:
  • Post category:vue


一、项目环境

用springboot做后端框架,Vue作为前端框架,实现前后分离,nginx作为代理服务器,cordova对Vue进行打包成APP。

二、Vue实现跨域,区分开发环境和生产环境的后台访问路径

1.新建globalApi.js,js中加入如下代码

//声明变量
let BASE_URL='';
//判断当前运行环境
if (process.env.NODE_ENV === "development") {
    //'/api'为vue.config.js中设置的proxy代理
    BASE_URL='/api'; 
}else {
    BASE_URL='http://192.168.0.15:8090/blog';
}
export default {
    BASE_URL
}

2.main.js中引用globalApi.js,代码如下

import global from './globleApi';
Vue.prototype.global = global;
//设置axio的baseurl
axios.defaults.baseURL = global.BASE_URL;

3.vue组件中通过axio获取后台数据方式

//直接访问后台路径
this.axios.get('/listBlog',{
             headers:{
                 "token":"AMBASSADORIAL"
             },

            })
                .then(  (response)=>{
                    if(response.data.code==200){
                        this.blogs=response.data.data;
                    }else{
                        console.log(response);
                    }

                })
                .catch(function (error) {
                     console.log(error);
                });

三、后台添加拦截器解决跨域请求

RemoteInterceptor.java

package com.tdrc.common.interceptor;

import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author dpf
 * @version 1.0
 * @date 2020-3-27 15:43
 * @instruction ...
 */
public class RemoteInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse resp, Object handler) throws Exception {
        //*号表示对所有请求都允许跨域访问
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Methods", "*");
        // 设置服务器允许浏览器发送请求都携带cookie
        resp.setHeader("Access-Control-Allow-Credentials","true");
        // 允许的访问方法
        resp.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE, PATCH");
        // Access-Control-Max-Age 用于 CORS 相关配置的缓存
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers","token,Origin,X-Requested-With, Content-Type, Accept,mid,X-Token,WG-Token");
        resp.setCharacterEncoding("UTF-8");
        /**设备默认值**/
        resp.setContentType("application/json;charset=UTF-8");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}

StartupConfig.java

package com.tdrc.common.config;

import com.tdrc.common.interceptor.RemoteInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class StartupConfig implements WebMvcConfigurer {
	@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RemoteInterceptor()).addPathPatterns("/**");
    }
    @Bean
    public RemoteInterceptor RemoteInterceptor() {
        return new RemoteInterceptor();
    }
}

三、web端环境部署

采用nginx服务器进行代理,直接访问nginx的地址即可,nginx.conf配置代码如下

 server {
        listen       8080;
        server_name  192.168.0.15;
        location / {
            #vue打包好的静态资源的存放路径
			root  D:\work-idea\frontend\vuecurd\dist;
			index  index.html index.htm;
			#try_files $uri $uri/ /index.html
		}
        #vue使用api作为代理时,在这需要进行说明
		#location /api/ {
		#  proxy_pass http://192.168.0.15:8090/blog/;
		#}

四、android

使用cordova打包好后,Android9不支持http,以下的版本支持,需要在AndroidManifest.xml文件中加入 <application  android:usesCleartextTraffic=”true”



版权声明:本文为doupengzp原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。