NodeJS 在express中为robots.txt渲染ejs模板

crcmnpdw  于 2023-02-08  发布在  Node.js
关注(0)|答案(3)|浏览(175)

我想在Express中使用robots.txt文件中的一些变量。
我怎样才能把这个文件呈现为一个EJS模板呢?我已经有了一个处理.html文件的EJS。

app.route('/robots.txt')
    .get(index.robotstxt);

/**
 * Send robotstxt file
 */
exports.robotstxt = function (req, res) {
    res.type('text/plain');
    res.render('robots.txt', {
        home: config.home
    });
};

# robotstxt.org

User-agent: *
Disallow: /settings
Disallow: /account/
Allow: /

sitemap: <%= home %>/sitemap.xml

目前,我只是得到以下错误:

Error: Cannot find module 'txt' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.require (module.js:364:17) at require (module.js:380:17) at new View (/Users/user/projects/app/node_modules/express/lib/view.js:43:49) at Function.app.render (/Users/user/projects/app/node_modules/express/lib/application.js:484:12) at ServerResponse.res.render (/Users/user/projects/app/node_modules/express/lib/response.js:777:7) at Object.exports.robotstxt [as handle] (/Users/user/projects/app/lib/controllers/index.js:29:6) at next_layer (/Users/user/projects/app/node_modules/express/lib/router/route.js:103:13) at Route.dispatch (/Users/user/projects/app/node_modules/express/lib/router/route.js:107:5)

模板的格式为./app/views/robots.txt

xqnpmsa8

xqnpmsa81#

我通过将./app/robots.txt移动到./app/views/robots.ejs使其工作

/**
 * Send robotstxt file
 */
exports.robotstxt = function (req, res) {
    res.type('text/plain');
    res.render('robots.ejs', { //use .ejs extension instead of .txt
        home: config.home
    });
};
o4tp2gmn

o4tp2gmn2#

我面对这个问题,我找到的解决方案是使用npm模块express-robots-txt

goucqfw6

goucqfw63#

您应该在ejs文件中呈现xml站点Map

app.route('/robots.txt').get(index.robotstxt);

exports.robotstxt = function (req, res) {
    res.type('text/plain');
    res.render('robots.ejs', {
        home: config.home
    });
};

这样,您的文件robots.ejs将包含xml数据,并且您将能够以www.yoursite.com/sitemap.xml的形式查看它

相关问题