最近有点时间,使用uniapp写一个随机联系英语的app/小程序。
只有前端的小程序做好了,因为为没有实名,所以只能通过二维码访问。

考虑是小程序是静态的,我平时也没有时间更新和维护小程序的内容,另外小程序对代码量有限制。所以准备再写一个后端,用来维护,小程序要求是ssl加密,我的测试服务器没有安装ssl证书。所以先考虑做个APP吧。闲言少叙,开始
找了一个springboot-manager(应该是2020年wenbin老师开源的一个框架),把后台架构做了一下后。
uniapp使用浏览器运行,出现跨域问题。查找资料,
springboot后端解决
1、更新原框架中的WebMvcConfigurer,路径可以查询代码中的文件包。
1
package com.company.project.common.config;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;
import java.io.File;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {
//其他代码不变
/**
* 页面跨域访问Controller过滤
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
WebMvcConfigurer.super.addCorsMappings(registry);
registry.addMapping("/**")
.allowedHeaders("*")
.allowedMethods("POST", "GET", "PUT", "DELETE")
.allowedOrigins("*")
.allowCredentials(true).maxAge(3600);
}
}
主要更新跨域部分的代码。
2、新建一个GlobalCorsConfig配置类,代码如下
1
package com.company.project.common.config;
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;
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedMethod("*");
config.addAllowedHeader("*");
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
3、在需要跨域处理的方法中增加 @CrossOrigin注释,这边演示我的英语试题内容查询的方法,示例代码为:
1
package com.company.project.controller;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.company.project.entity.LevelTableEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.company.project.common.utils.DataResult;
import com.company.project.entity.LevelContentEntity;
import com.company.project.service.LevelContentService;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
@Controller
@RequestMapping("/")
public class LevelContentController {
@Autowired
private LevelContentService levelContentService;
@CrossOrigin(origins = "http://localhost:8081",allowCredentials = "true")
@ApiOperation(value = "查询数据")
@GetMapping("levelContent/list")
@SaCheckPermission("levelContent:list")
@ResponseBody
public DataResult findList(LevelContentEntity levelContent){
LambdaQueryWrapper<LevelContentEntity> queryWrapper = Wrappers.lambdaQuery();
if(!StringUtils.isEmpty(levelContent.getCreateId())){ queryWrapper.eq(LevelContentEntity::getCreateId,levelContent.getCreateId()); }
queryWrapper.eq(levelContent.getLevelId() != null,LevelContentEntity::getLevelId,levelContent.getLevelId());
return DataResult.success(levelContentService.list(queryWrapper));
}
}
以上三步即可解决跨域的问题。
uniapp使用webview调试无法保存和发送cookie
上面解决了跨域的问题,浏览器控制台不再出现跨域的错误,但是数据查不到,报302的错误,框架使用的是cookie,浏览器调试发现登录后,可以获取后端返回的cookie,但是登录有发送不自动协调cookie?
查阅资料,uni.request发送请求如果跨域的话,需要配置withCredentials: true。
示例代码为
1
login(){
uni.request({
url:baseurl.baseurl+"/app/sys/user/login",
method:'POST',
data:{
username:this.username,
password:this.passwd
},
withCredentials: true, // 允许跨域携带/保存 Cookie(核心中的核心)
// crossDomain: true,
success:(res)=>{
if(res.data.code==0){
uni.clearStorage()
uni.setStorageSync("uid",res.data.data.id)
uni.reLaunch({
url:'/pages/onlinepage/onlinepage'
})
}else{
uni.showToast({
title: '用户名密码错误,请重新输入',
duration: 2000,
icon:'error'
}) }
}
})
},
然后在使用携带cookie发送请求是也需要配置该项:示例为:
1
getData() {
uni.request({
url: baseurl.baseurl + "/levelContent/list",
withCredentials: true, // 允许跨域携带/保存 Cookie(核心中的核心)
data:{"createId":uni.getStorageSync("uid")},
success: (res) => {
console.log(res)
}
})
}
至此完成了使用webview的跨域以及cookie验证的调试。目前小程序不支持cookie,找时间还需要更新后端的验证方式为token。
但有些后端无法调整的,且只需要H5的情况,可能还会使用响应的技术。
特此记录分项。