由于我的Express路由中的某些内容,数据似乎被发送两次到Angular前端。这似乎将Mixpanel发送到一个无限循环,导致部分应用程序无法正常加载。
以下代码的原因是我想检测某些用户代理并向其发送除常规用户看到的内容之外的其他代理。这是因为某些用户代理不会加载Javascript,但我需要它们从页面中抓取一些信息。
来自我的 server.js :
git commit -m "Init"
来自我的 home.js :
app = express();
app
.use( morgan( 'dev' ) )
.use(bodyParser.urlencoded( { limit: '50mb', extended: true } ) )
.use( bodyParser.json( { limit: '50mb' } ) )
.use( '/api', require('./routes/usersRoute.js') )
.use( express.static( indexPath ) )
.all( '/*', require( './routes/home.js' ) )
几页似乎坏了,我不确定为什么有些页面会破坏而有些页面会破坏。值得注意的是,我试图在router.get( '/:user/:stream/:slug', function( req, res, next ) {
if ( req.headers['user-agent'].indexOf( 'facebook' ) != -1 ) {
if ( !req.params.user && !req.params.stream && !req.params.slug ) return next()
contentController.findUserId( req.params.user )
.then( function ( userId ) {
if ( !userId ) return next()
contentController.projectContent( req.params.slug )
.then( function ( item ) {
if ( !item ) return next()
createOpenGraph( item[0] )
.then( function ( OG ) {
return res.status( 200 ).send( OG )
})
.catch( function ( error ) {
console.log( error )
return res.status( 500 ).json( error )
})
})
})
} else {
return res.status( 200 )
.set( { 'content-type': 'text/html; charset=utf-8' } )
.sendFile( indexPath )
}
})
router.get( '/*', function( req, res ) {
return res.status( 200 )
.set( { 'content-type': 'text/html; charset=utf-8' } )
.sendFile( indexPath )
})
.get( '/:user/:stream/:slug'...)
函数中检测到的页面中断了。在该页面上,在控制台中,我可以看到角度加载两次的错误,这证实了由于双响应问题导致Mixpanel断开。此错误不会出现在不中断的页面上。更进一步,我可以看到每次在破坏的页面上加载时都会调用两个函数(在home.js
中),而不是在工作中加载。
我愿意接受有关如何做得更好的所有建议。
答案 0 :(得分:1)
您已在任何其他匹配路由之前定义要在routes/home.js
文件上调用的路由。因此,您需要将控件传递给执行下一个参数的下一个路径。
您可能希望在另一条路线上发送文件,可能在.use( '/app', require('./routes/appRoutes.js') )
上或在示例上的最后一个方法上发送。
router.get( '/:user/:stream/:slug', function( req, res, next ) {
if ( req.headers['user-agent'].indexOf( 'facebook' ) != -1 ) {
/*Do the facebook stuff*/
} else {
res.status( 200 );
}
next();
});
// routes / appRoutes.js
router.get( '/*', function( req, res, next ) {
return res.status( 200 )
/*Set you headers independently on the api routes as you might prefer to set the content type to application/json*/
.set( { 'content-type': 'text/html; charset=utf-8' } )
.sendFile(indexPath ).end();
});
// server.js
app = express();
app.use( morgan( 'dev' ) )
.use(bodyParser.urlencoded( { limit: '50mb', extended: true } ) )
.use( bodyParser.json( { limit: '50mb' } ) )
.use( '/api', require('./routes/usersRoute.js') )
.use( '/app', require('./routes/appRoutes.js') )
.use( express.static( indexPath ) )
.all( '/*', require( './routes/home.js' ) );