【问题标题】:Vue Router history mode with Express and nginx reverse proxy带有 Express 和 nginx 反向代理的 Vue Router 历史模式
【发布时间】:2017-05-23 13:57:15
【问题描述】:

我已将 nginx 配置为将所有请求传递给 Node:

server {
    listen 80;
    server_name domain.tld;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

在服务器上,我有一个运行 Express 的 Node 应用程序,它为我的 Vue 索引文件提供服务。

app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/app/index.html`);
});

我想在 Vue 路由器中使用 HTML5 历史模式,所以我在路由器设置中设置了mode: 'history'。我安装了connect-history-api-fallback 并进行了设置:

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

如果用户第一次点击http://domain.tld,路由就可以正常工作。但是,如果直接访问子路由,或者刷新页面,我会得到一个未找到的错误。

如何更改我的配置?

【问题讨论】:

  • 使用节点应用程序提供文件是否明智?使用例如不是更好吗? nginx 在资源方面?

标签: node.js express nginx vue-router


【解决方案1】:

我遇到了同样的问题。

下单时不起作用:

app.use(express.static('web'));
app.use(history());

,但在以下情况下会起作用:

app.use(history());
app.use(express.static('web'));

整个示例应用:

var express = require('express');
var history = require('connect-history-api-fallback');
var app = express();

app.use(history());
app.use(express.static('web'));

app.listen(3002, function () {
    console.log('Example app listening on port 3002!')
});

网络文件夹 我有:
index.html
和其他js、css文件。

【讨论】:

  • 不明白你的答案为什么没有被认为是正确的。这为我修复了它,我现在可以使用该包
  • 是的!这为我修复了它,artuu 你能解释为什么交换历史/静态修复它吗?
【解决方案2】:

由于无法使 connect-history-api-fallback 库正常工作,我自己创建了一个:

app.use((req, res, next) => {
  if (!req.originalUrl.includes('/dist/', 0)) {
    res.sendFile(`${__dirname}/app/index.html`);
  } else {
    next();
  }
});

当请求除脚本和图像所在的/dist 之外的任何内容时,这将发送/app/index.html

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 2018-02-09
    • 2016-03-31
    • 2017-09-27
    • 1970-01-01
    • 2021-01-29
    • 2018-12-12
    • 2021-10-20
    • 2018-07-07
    相关资源
    最近更新 更多