0
点赞
收藏
分享

微信扫一扫

【前端素材】推荐优质在线高端蜂蜜商城电商网页Beejar平台模板(附源码)

mafa1993 03-02 07:30 阅读 5

一、问题描述

我们把Vue项目的路由模式,设置成history
然后,build
并把dist中的代码部署到node+express服务中
访问页面后,刷新页面报404问题
在这里插入图片描述

二、原因分析

server.js文件
会发现,文件中配置的路径没有Vue项目中对应的路径
所以,刷新页面时,报404
这也是history模式的一个小问题。

const express = require('express')
const app = express()
app.use(express.static(__dirname+'/static'))

app.get('/students',(request,response)=>{
	const students = [
		{id:'001',name:'tom',age:18},
		{id:'002',name:'jerry',age:19},
		{id:'003',name:'tony',age:120},
	]
	response.send(students)
})

app.listen(5000,(err)=>{
	if(!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5000/students');
})

三、解决

这个问题的本质,是请求路径在后端没对应上
所以,要解决这个问题,需要从后端代码着手

我这里用的是node+express部署项目
就这个情况,来解决

1、安装connect-history-api-fallback中间件

npm i connect-history-api-fallback

2、修改server.js
关键代码:

const history = require('connect-history-api-fallback')
app.use(history())

完整配置:

const express = require('express')
const history = require('connect-history-api-fallback')

const app = express()
app.use(history())
app.use(express.static(__dirname+'/static'))

app.get('/students',(request,response)=>{
	const students = [
		{id:'001',name:'tom',age:18},
		{id:'002',name:'jerry',age:19},
		{id:'003',name:'tony',age:120},
	]
	response.send(students)
})

app.listen(5000,(err)=>{
	if(!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5000/students');
})

重启项目,即可。
此时,刷新页面,不会报404问题。

举报

相关推荐

来客推电商商城小程序源码

0 条评论