express react build被卡在非索引文件的路径上加载

时间:2019-07-07 14:24:08

标签: node.js express

我有一个明确的反应申请

我在使构建像没有构建一样可以正常工作时遇到了问题。

执行npm start时,我只能到达索引路径/

但是,如果我这样做了localhost:3000/login。它只是无限加载。并最终导致未收到数据错误。

  

注意:反应和表达方面可以很好地协同工作,但是当   建立即时通讯收到此错误。这在这里有效-> "startdev": "concurrently --kill-others \"npm run client\" \"npm run server\" ",

但是我需要这个作为构建文件。

这行代码可能有问题吗?

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname+'/client/public/index.html'));

})

这是获取反应构建的main.js

main.js

import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from 'morgan';
import path from 'path';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import userRoute from './routes/users';
import imageRoute from './routes/images';
import passport from 'passport';
import session from 'express-session';
import './config/passport';
import knex from 'knex';
import config from './knexfile'
import KnexSessionStore from 'connect-session-knex';
........
app.use(logger('dev'));
// For React Stuff if need be
app.use(express.static(path.join(__dirname, 'client/build')));

//
app.use(cookieParser());
app.use(bodyParser.json());
// you need body parser urlencoded so passport will not give a Missing Credentials error
app.use(session({
  store: store, 
  saveUninitialized: false,
  resave:false,
  cookie: {   maxAge: 30 * 24 * 60 * 60 * 1000 },  // 30 days
  secret : process.env.JWT_SECRET,

}));

app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended:false})); 
app.use(cors({
  origin:process.env.ALLOW_ORIGIN,
  credentials: true,
  allowedHeaders: 'X-Requested-With, Content-Type, Authorization',
  methods: 'GET, POST, PATCH, PUT, POST, DELETE, OPTIONS',
  exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar'],
}))

app.get('/', (req, res) => {
  res.send('Hello World!');
});
app.use('/users', userRoute);
app.use('/images', imageRoute);
// app.use('/images', imageRoute);
// app.use('/comments', imageRoute);
app.use(() => (req, res, next)  =>{
  res.locals.user = req.user; // This is the important line
  // req.session.user = user
  console.log(res.locals.user);
  next();
});

app.use('/', function (req, res, next) {
  var n = req.session.views || 0
  req.session.views = ++n
  res.end(n + ' views')
  console.log(n);
})


//build mode
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname+'/client/public/index.html'));

})


// module.parent prevents the 
// Node / Express: EADDRINUSE, Address already in use error when unit testing
if(!module.parent){
  app.listen(PORT, () =>
    console.log(`Example app listening on port ${process.env.PORT}!`),
  );
 }

export default app;

1 个答案:

答案 0 :(得分:0)

解决了。

我只是将构建逻辑移到了路径和核心之前。现在可以在heroku上使用了,我可以在不同的路径之间切换。

app.use(express.static(path.join(__dirname, 'client/build')));

app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '/client/build/index.html'));
})

app.use(cors({
  origin:process.env.ALLOW_ORIGIN,
  preflightContinue: false,
  credentials: true,
  allowedHeaders: 'X-Requested-With, Content-Type, Authorization',
  methods: 'GET, POST, PATCH, PUT, POST, DELETE, OPTIONS',
  exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar'],
}))
...

完整代码

import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import logger from 'morgan';
import path from 'path';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import userRoute from './routes/users';
import imageRoute from './routes/images';
import passport from 'passport';
import session from 'express-session';
import './config/passport';
import knex from 'knex';
import config from './knexfile'
import KnexSessionStore from 'connect-session-knex';
const PORT = process.env.PORT || 3000
const knexSession = KnexSessionStore(session);
const herokuOrNot = process.env.NODE_ENV !== 'production' ? config.development : config.production
const myKnex = knex(herokuOrNot);
const store = new knexSession({
  knex:myKnex,
  // tablename:'sessions'
})
const app = express();
// declare this build before routes and stuff. else it wont go to the routes. 
if (process.env.NODE_ENV === 'production'){
  app.use(express.static(path.join(__dirname, 'client/build')));

  app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '/client/build/index.html'));
  })

}
app.use(cors({
  origin:process.env.ALLOW_ORIGIN,
  preflightContinue: false,
  credentials: true,
  allowedHeaders: 'X-Requested-With, Content-Type, Authorization',
  methods: 'GET, POST, PATCH, PUT, POST, DELETE, OPTIONS',
  exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar'],
}))
if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}
app.use(logger('dev'));
// For React Stuff if need be
//
app.use(cookieParser());
app.use(bodyParser.json());
// you need body parser urlencoded so passport will not give a Missing Credentials error
app.use(session({
  store: store, 
  saveUninitialized: false,
  resave:false,
  cookie: {   maxAge: 30 * 24 * 60 * 60 * 1000 },  // 30 days
  secret : process.env.JWT_SECRET,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended:false})); 
app.get('/', (req, res) => {
  res.send('Hello World!');
});
app.use('/users', userRoute);
app.use('/images', imageRoute);
// app.use('/images', imageRoute);
// app.use('/comments', imageRoute);
app.use(() => (req, res, next)  =>{
  res.locals.user = req.user; // This is the important line
  // req.session.user = user
  console.log(res.locals.user);
  next();
});
app.use('/', function (req, res, next) {
  var n = req.session.views || 0
  req.session.views = ++n
  res.end(n + ' views')
  console.log(n);
})
// module.parent prevents the 
// Node / Express: EADDRINUSE, Address already in use error when unit testing
if(!module.parent){
  app.listen(PORT, () =>
    console.log(`Example app listening on port ${process.env.PORT}!`),
  );
 }
export default app;