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

ⅰ亾dé卋堺 提交于 2019-12-11 04:26:25

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/50662060/configure-production-environment-in-a-create-react-appsyntaxerror-unexpected-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!