在create-react-app中配置生产环境(SyntaxError:JSON中位置0处的意外令牌<) [英] Configure production environment in a create-react-app(SyntaxError: Unexpected token < in JSON at position 0)

查看:174
本文介绍了在create-react-app中配置生产环境(SyntaxError:JSON中位置0处的意外令牌<)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中配置生产环境(使用create-react-app)。
也许这是一个愚蠢的问题,因为我正在搜索,并且有很多与此相关的文章,但是这些都对我没有帮助。另外,我在create-react-app

解决方案

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

 让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 是我的前端文件夹的名称,其中包括为生产而创建的build文件夹。 (我将前端文件夹放在服务器端文件夹中)



此链接对我有帮助。
语法错误:意外令牌< #1812



希望这对其他人有帮助。


I want to configure production environment in my app (using create-react-app). Maybe it's a silly question to ask because I'm searching and there are lots of articles about this but none of this helped me. Also, I used codes in create-react-app here(production) and here(development) but still not working.

For server side, I'm using node and all API are working well with development mode in react. but when I'm using production mode It's not working.

It's just returning

SyntaxError: Unexpected token < in JSON at position 0

in the browser console.

I can't access my routes in the server in production mode.

How can I solve it? Help appreciated.

This is my app tree, front-end folder includes my react code and running on a different port (server: 3000, react: production:3001, development:5000). I have added this lines of code to 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'));
 });

and this in www.js:

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

解决方案

I found my answer and my app is working in production mode now, and I have deployed it. I just added this lines into my app.js in the root directory in server-side code(node application):

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();
  });

Here myapp is the name of my project folder(server-side) and fron-end is the name of my front-end folder that includes builds folder that has created for production. (I put my front-end folder inside server-side folder)

This link helps me. Uncaught SyntaxError: Unexpected token < #1812

Hope this helps others.

这篇关于在create-react-app中配置生产环境(SyntaxError:JSON中位置0处的意外令牌&lt;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆