Configure production environment in a create-react-app(SyntaxError: Unexpected token < in JSON at position 0)

Configure production environment in a create-react-app(SyntaxError: Unexpected token < in JSON at position 0)

我想在我的应用程序中配置生产环境(使用 create-react-app)。 也许这是一个愚蠢的问题,因为我正在搜索并且有很多关于此的文章,但是 none 其中对我有帮助。此外,我在 create-react-app here(production) and here(开发)中使用了代码,但仍然无法正常工作。

对于服务器端,我使用的是节点,并且所有 API 在 React 开发模式下运行良好。但是当我使用生产模式时它不起作用。

刚回来

SyntaxError: Unexpected token < in JSON at position 0

在浏览器控制台中。

我无法在生产模式下访问服务器中的路由。

我该如何解决?帮助表示赞赏。

这是我的应用程序树,前端文件夹包括我的反应代码和 运行 在不同的端口(服务器:3000,反应:production:3001,development:5000)。 我已将这行代码添加到 app.js :

app.use(express.static(path.join(__dirname, 'front-end/build')));
 app.get('*', function (req, res) {
 res.sendFile(path.join(__dirname, 'front-end/build', 'index.html'));
 });

和 www.js 中的这个:

if (process.env.NODE_ENV === 'production') {
app.use(express.static('front-end/build'));
 }

我找到了答案,我的应用程序现在可以在生产模式下运行,并且我已经部署了它。 我刚刚在服务器端代码(节点应用程序)的根目录中将这些行添加到我的 app.js 中:

let root = path.join(__dirname, '..', 'myapp/fron-end/build');
  app.use(express.static(root));
  app.use(function(req, res, next) {
  if (req.method === 'GET' && req.accepts('html') && !req.is('json') && 
     !req.path.includes('.')) {
         res.sendFile('index.html', { root });
    } else next();
  });

这里 myapp 是我的项目文件夹(服务器端)的名称, fron-end 是我的前端的名称-包含为生产创建的构建文件夹的结束文件夹。 (我把我的前端文件夹放在服务器端文件夹里)

这个link对我有帮助。 Uncaught SyntaxError: Unexpected token < #1812

希望这对其他人有帮助。