簡體   English   中英

ExpressJS 重定向索引.html

[英]ExpressJS redirect index.html

JS,

我有一個包含一些路線的快速應用程序。 當我的路由器不匹配任何路由時,它將顯示 index.html 而不是去路由“/*”並重定向到特定路由。

I don't understand why my router doesn't go to app.get('/*') because when I type https://my-domain.com I want to be redirect to https://my-domain.com/test?id=1 也許我可以用 express-static 做點什么,但我不知道怎么做。

如果我將我的文件命名為home.html而不是index.html ,它就可以完美地工作。

這是我的一小段代碼:

const express = require('express');
const path = require('path');
const cors = require('cors');
const app = express();
const bodyParser = require("body-parser");
const ejs = require('ejs');
const csrf = require('csurf');

const port = 3080;

let csrfProtection = csrf({ cookie: true })

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(csrfProtection);
app.engine('html', ejs.renderFile);
app.set('view engine', 'html');

app.use(function (err, req, res, next) {
    if (err.code !== 'EBADCSRFTOKEN') return next(err)

    res.status(403).json({error: "Invalid CSRF Token"});
})

app.post('/roles', csrfProtection, (req, res) => {
    /*...*/
});

app.get('/test', csrfProtection, (req, res) => {
    /*...*/
});


app.all('/*', csrfProtection, (req,res) => {
    if(Object.keys(req.query).length == 0) {
        res.redirect("https://my-domain.com/test?id=1");
    }
    res.render(path.join(__dirname + '/index.html'), {csrfToken: req.csrfToken()});
});


app.listen(port, () => {
    console.log(`Server listening on the port::${port}`);
});

我的文件結構是:

    • static
      • css
      • js
    • 索引.html
    • index.js

在請求https://my-domain.com時,寫入res.redirect('/foo/bar') ,其中 /foo/bar 是您想要重定向到的 Z572D4E421E5E6B9BC11D815E8A027112。

res.redirect()參見官方文檔: http://expressjs.com/en/api.html#res.redirect

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM