无法访问我的站点中的链接(复制和粘贴):Node.js - Express.js - Webpack - Vue.js - historymode [英] Unable to acess links (copying and pasting) whitin my Site : Node.js - Express.js - Webpack - Vue.js - historymode

查看:28
本文介绍了无法访问我的站点中的链接(复制和粘贴):Node.js - Express.js - Webpack - Vue.js - historymode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近创建了一个基于 Node.js、Express.js 和 Vue.js 的网站,并在历史模式下使用路由器和 Webpack.由于是单页应用程序,我安装了 express-history-api-fallback 并且到目前为止它工作得很好但是(一如既往地有但是)由于某些原因我不理解某些网址,我得到了一个白页以及一些错误,例如:

I recently created a website with base on Node.js, Express.js and Vue.js with router in history mode and Webpack. Since is a Single Page Application, I installed express-history-api-fallback and it works quite fine so far but (as always there is a but) for some reasons that I'm not understanding for some urls, i get a white page and some errors like:

Uncaught SyntaxError: Unexpected token '<'          ------        manifest.61d5cd8248647cdb144a.js:1
Uncaught SyntaxError: Unexpected token '<'          ------        vendor.db7271094dc9fcde8b9f.js:1
Uncaught SyntaxError: Unexpected token '<'          ------        app.3cfe27cef1608de00b06.js:1 

我不明白问题是在我的 webpack conf 文件中还是在我的 node.js 中(我猜与前端有关,因为我没有看到任何传入的请求)或我的 vue-路由器.

I don't understand whether the problem is within my webpack conf file or withing my node.js (I guess is related to the front-end cause I'm not seeing any incoming request in the be) or in my vue-router.

我不明白的原因(除了缺乏知识)是,如果我尝试访问我的 Vue 应用程序中的页面,单击链接(即访问格式为 mywebsiteinexample.com 的用户个人资料页面)/user/userId) 它可以工作,但如果我刷新页面,我只能看到一个白页,并且在控制台内,我会看到上面写的错误.

The reason why I don't understand (apart of lack of knowledge) is that if I try to access to a page within my Vue app, clicking on a link (i.e. accessing to an user's profile page formatted as mywebsiteinexample.com/user/userId) it works but if i refresh the page I'm just able to see a white page and, inside the console, the errors I wrote about above.

我的文件的一般架构:

我想这里有一些有用的代码:

here are some, I guess, useful peaces of code:

Server.js

const express = require('express')
const fallback = require('express-history-api-fallback')
const path = require('path')

const historyModeHandlerHTTP = express()
const root = `${__dirname}/../`
historyModeHandlerHTTP.use(express.static(root))
historyModeHandlerHTTP.use(fallback(path.join(__dirname + '/../index.html')))

historyModeHandlerHTTP.listen(80, () => {
    console.log('HTTP Server on')
})

Webpack.prod.conf.js

'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const {
  CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

const env = require('../config/prod.env')

const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : false,
  output: {
    path: config.build.assetsRootMain,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.ProgressPlugin(),
    new CleanWebpackPlugin({
      dry: false,
      cleanOnceBeforeBuildPatterns: [config.build.assetsSubDirectory + '*/js/*', config.build.assetsSubDirectory + '*/css/*']
    }),
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
    new ExtractTextPlugin({
      filename: utils.assetsPath('css/[name].[contenthash].css'),
      allChunks: true,
    }),
    new OptimizeCSSPlugin({
      cssProcessorOptions: config.build.productionSourceMap ?
        {
          safe: true,
          map: {
            inline: false
          }
        } :
        {
          safe: true
        }
    }),
    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: 'template.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: false,
        removeAttributeQuotes: true
      },
      chunksSortMode: 'dependency'
    }),
    new webpack.HashedModuleIdsPlugin(),
    new webpack.optimize.ModuleConcatenationPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks(module) {
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      minChunks: Infinity
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'app',
      async: 'vendor-async',
      children: true,
      minChunks: 3
    }),

    new CopyWebpackPlugin([{
      from: path.resolve(__dirname, '../static'),
      to: config.build.assetsSubDirectory,
      ignore: ['.*']
    }])
  ]
})

if (config.build.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

const config = require('../config')

const path = require('path')

module.exports = {
    dev: {
        // Paths
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {},

        // Various Dev Server settings
        host: 'localhost',
        port: 8080, 
        autoOpenBrowser: false,
        errorOverlay: true,
        notifyOnErrors: true,
        poll: false,
        devtool: 'cheap-module-eval-source-map',
        cacheBusting: true,
        cssSourceMap: true
    },

    build: {
        // Template for index.html
        index: path.resolve(__dirname, '../../index.html'),

        // Paths
        assetsRoot: path.resolve(__dirname, '../dist'),
        assetsRootMain: path.resolve(__dirname, '../../'),
        assetsSubDirectory: 'front-end/static',
        assetsPublicPath: '',
        mainfile : 'front-end/src/main.js',
        routerfile : 'front-end/src/router/index.js',
        constantsFile : 'utils-bf/constants.js',
        productionSourceMap: true,
        devtool: '#source-map',
        productionGzip: false,
        productionGzipExtensions: ['js', 'css'],
        bundleAnalyzerReport: process.env.npm_config_report
    }
}

推荐答案

[SOLUTION]

问题与Webpack的配置有关!如果有人遇到同样的问题,只需设置 PublicPath : '/'

The Problem was related to the configuration of Webpack! If anyone is facing the same problem, just set the PublicPath : '/'

  output: {
    publicPath: '/',
    path: config.build.assetsRootMain,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },

这篇关于无法访问我的站点中的链接(复制和粘贴):Node.js - Express.js - Webpack - Vue.js - historymode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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