Lighthouse 读取我的索引而不是 robots.txt

Pie*_*ran 5 robots.txt reactjs

我想在我的 React 应用程序上使用 chrome 审核工具,但它一直说我的 robots.txt 文件无效。问题是,该文件似乎非常好,只是它不读取 robots.txt,而是读取我的 index.html 文件,因此导致此错误:

在此处输入图片说明

这两个文件都在我的 /public 文件夹中,为什么它会读取索引文件?

Han*_*ngh 1

如果您使用Node 和 Express来在生产环境中运行React App项目。如果您的服务器文件代码如下所示,这意味着您正在为所有请求(路由)提供相同的文件。在灯塔审核期间,浏览器向http://localhost:5000/robots.txt发出 get 请求,作为回报,它会得到index.html服务。

 app.get('/*', function (req, res) {
   res.sendFile(path.join(__dirname, 'build', 'index.html'));
 });
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,您可以在上面的代码片段之前添加robots.txt文件的路由,如下所示。

 app.get('/robots.txt', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'robots.txt'));
});

app.get('/*', function (req, res) {
   res.sendFile(path.join(__dirname, 'build', 'index.html'));
 });
Run Code Online (Sandbox Code Playgroud)