admin管理员组

文章数量:1633932

问题描述

当前端使用路由功能后,做的静态页没有任何问题。但和后端服务放到一块后,直接访问路由就会出错,导致404错误。

问题原因

导致这类问题的原因是,直接地址访问前端路由的地址会先请求服务器,可服务器又未对此路由进行处理,服务器没找到访问地址相关的路由就返回给前台404.

解决方法

koa2服务端

const Koa = require('koa');
const app = new Koa();
app.use( async ( ctx ) => {
  console.log(333);
  if ( ctx.url === '/index' ) {
    ctx.body = 'cookie is ok'
  }else{
    //index.html为前台访问入口文件
    ctx.response.type = 'html';
    ctx.response.body = fs.createReadStream('./dist/index.html');
  }
})

Express服务端

//sendFile()由express提供,所以不适用于其它服务

const express = require('express')
const app = express()
app.get('*', function (request, response){
  response.sendFile(path.resolve(__dirname, 'dist', 'index.html'))
})

其它

如果是其它服务端,原理一样,当后端未匹配到路由全都指向前端,由前端路由处理,如果前端路由也未匹配到,由前端来完成404,500等状态。

本文标签: 路由后端冲突方法