javascript - connect-history-api-fallback 防止 API 调用
问题描述
我将connect-history-api-fallback与page.js 路由器结合使用。
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);
});
解决方案
这使它工作。
app.use(history({
rewrites: [
{
from: /^\/api\/.*$/,
to: function(context) {
return context.parsedUrl.path
}
}
]
}))
推荐阅读
- python-3.7 - 如何在python中重复输入?
- excel - 将 Excel 幂查询表列转换为字符串
- php - 在我的沙盒帐户的仪表板中显示订单的流程是什么?
- php - 如何获得我的广告组预算可以获得的点击次数和展示次数?
- c# - 一些特定条件的正则表达式
- typescript - 为什么我不能从 Typescript 中的方法动态设置样式
- python - Scikit-learn:RuntimeError:scikit-learn 估计器应始终在其 __init__ 的签名中指定其参数
- typescript - Typescript“+”运算符如何与泛型和函数一起使用?
- android - AndroidX没有找到类“android.support.v4.content.ContextCompat
- asp.net - 身份框架使用主体