uni-app 部署h5时,按F5刷新内页,报404

描述问题

由于 uni-app 路由使用 history模式,导致刷新内页报404错误

解决

  1. 在服务器端做处理:报404就跳转到登录页
  2. 在登录页中做判断,如果有用户id,就表示登录成功,跳转到首页

后端处理404错误

注意:使用springboot框架时,需要做些改动

package top.malaoshi.netdisk.ctrl;

import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.DispatcherServlet;
import top.malaoshi.netdisk.vo.JsonResult;
import top.malaoshi.util.DateTime;
import top.malaoshi.web.utils.Ajax;
import top.malaoshi.web.utils.ResponseUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class MyBasicErrorController extends BasicErrorController {

    @Override
    public Object error(HttpServletRequest request, HttpServletResponse response, Exception e) {

        HttpStatus status = getStatus(request);
        if(Ajax.isAjax(request)){
            try {
                Map map = new HashMap();
                map.put("timestamp", DateTime.now("yyyy-MM-dd HH:mm:ss.SSS"));
                map.put("status",status.value());
                map.put("error",status.getReasonPhrase());
                map.put("message",e.getMessage());
                map.put("path",request.getServletPath());
                JsonResult jsonResult = JsonResult.fail(status.value(), e.getMessage(), map);
                ResponseUtils.sendJSON(response,status.value(), jsonResult);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }else{
            if(status.value() == 404){
                String servletPath = request.getContextPath();
                try {
                    response.sendRedirect(servletPath);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }

        return null;
    }

}

前端登录页处理

登录页做判断,如果有用户id,就表示登录成功,跳转到首页

onLoad() {
    /*
     history路由刷新报404错误
     在服务器端做处理:报404就跳转到登录页
     在登录页中做判断,如果有用户id,就表示登录成功,跳转到首页
     */
    const uid = getUid()
    if(uid !== "" ){
        uni.setStorageSync('index_ajax_type', "init")
        uni.redirectTo({
            url:'./note/index'
        })
    }
},

参考:
https://blog.csdn.net/weixin_39921970/article/details/124407702
https://blog.csdn.net/lianzhang861/article/details/112437213