vue项目,直接访问url ,404
如果您在直接访问 Vue 项目的某个 URL 时遇到 404 错误,那么可能是由于路由模式或服务器配置问题。
Vue Router 提供了两种模式:hash
和 history
。默认情况下,它使用 hash
模式,这个模式使用 URL 的 hash 来模拟一个完整的 URL,因此当 URL 改变时页面不会重新加载。但如果你使用 history
模式,URL 就会像正常的 url,例如:http://yoursite.com/user/id
,然后刷新页面就会返回 404,这是因为服务器找不到给定的路由。
如果你使用的是 history
模式,那么你需要在服务器端添加一些配置。对于一个基本的静态文件服务器,你需要配置你的服务器使得对于所有路由都返回 index.html
文件。
以下是一些常见服务器的配置方法:
Apache
在 .htaccess
文件中添加:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Nginx
在 Nginx 站点配置文件中添加:
location / {
try_files $uri $uri/ /index.html;
}
Express
如果你的服务器是 Express,可以使用 connect-history-api-fallback
中间件:
const express = require('express');
const history = require('connect-history-api-fallback');
const app = express();
app.use(history());
app.use(express.static(__dirname + "/dist"));
app.listen(5000);
注意:以上只是一些基础的配置示例,实际情况可能会因你的项目和服务器设置而有所不同。