connect-history-api-fallback防止API调用

问题描述 投票:0回答:1

我将connect-history-api-fallbackpage.js router结合使用。

page('/', index);
page('/about', about);
page();

function index() {
    console.log("viewing index");
}

function about() {
    console.log("viewing about");
}

路由工作正常,但是当我尝试访问API时,路由阻止了该调用。

GET localhost:4000/            # index view function
GET localhost:4000/about       # about view function
GET localhost:4000/api/todos   # Nothing, instead of JSON

这里是服务器...

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

var todos = require("./api/routes/todos");

var app = express();

// Allow requests from all domains and localhost
app.all("/*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header(
        "Access-Control-Allow-Headers",
        "X-Requested-With, Content-Type, Accept"
    );
    res.header("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE");
    next();
});

const root = `${__dirname}/app/dist`

app
    .use(history())
    .use(express.static(root))
    .use(express.json())
    .use(todos)
    ;

var server = app.listen(4000, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log("app listening at http://%s:%s", host, port);
});
javascript express routing single-page-application
1个回答
0
投票

这使它起作用。

app.use(history({
    rewrites: [
      {
        from: /^\/api\/.*$/,
        to: function(context) {
            return context.parsedUrl.path
        }
      }
    ]
 }))
© www.soinside.com 2019 - 2024. All rights reserved.