首页 > 解决方案 > 当使用香草水疗中心时,我有一个错误 router.js:66 GET http://localhost:3000/views/Category.html 404 (Not Found)

问题描述

我有一个关于香草 JS 的项目,我使用 Webpack。我用 spa 改变了 html 容器的内容。我通过这篇文章https://medium.com/better-programming/js-vanilla-script-spa-1b29b43ea475写了 spa 。但我有一个错误 router.js:66 GET http://localhost:3000/views/Category.html 404 (Not Found)。我的代码有什么问题?我的标题保持不变,只有主容器的内容发生了变化。我的项目结构:

-src
 -routing
  -route.js
  -router.js
 -views
  -Category.html
  -Page2.html
 -app.js
 -index.html
 -style.css

代码:route.js:

'use stict';

let Route = function (name, htmlName, defaultRoute) {
    try {
        if(!name || !htmlName) {
            throw 'error: name and htmlName params are mandatories';
        }
        this.constructor(name, htmlName, defaultRoute);
    } catch (e) {
        console.error(e);
    }
}

Route.prototype = {
    name: undefined,
    htmlName: undefined,
    default: undefined,
    constructor: function (name, htmlName, defaultRoute) {
        this.name = name;
        this.htmlName = htmlName;
        this.default = defaultRoute;
    },
    isActiveRoute: function (hashedPath) {
        return hashedPath.replace('#', '') === this.name; 
    }
}

export default Route;

路由器.js:

'use strict';

let Router = function (routes) {
    try {
        if (!routes) {
            throw 'error: routes param is mandatory';
        }
        this.constructor(routes);
        this.init();
    } catch (e) {
        console.error(e);   
    }
}

Router.prototype = {
    routes: undefined,
    rootElem: undefined,
    constructor: function (routes) {
        this.routes = routes;
        this.rootElem = document.getElementById('main');
    },
    init: function () {
        var r = this.routes;
        (function(scope, r) { 
            window.addEventListener('hashchange', function (e) {
                scope.hasChanged(scope, r);
            });
        })(this, r);
        this.hasChanged(this, r);
    },
    hasChanged: function(scope, r){
        if (window.location.hash.length > 0) {
            for (var i = 0, length = r.length; i < length; i++) {
                var route = r[i];
                if(route.isActiveRoute(window.location.hash.substr(1))) {
                    scope.goToRoute(route.htmlName);
                }
            }
        } else {
            for (var i = 0, length = r.length; i < length; i++) {
                var route = r[i];
                if(route.default) {
                    scope.goToRoute(route.htmlName);
                }
            }
        }
    },
    goToRoute: function (htmlName) {
        (function(scope) { 
            var url = 'views/' + htmlName,
                xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (this.readyState === 4 && this.status === 200) {
                    scope.rootElem.innerHTML = this.responseText;
                }
            };
            xhttp.open('GET', url, true);
            xhttp.send();
        })(this);
    }
};

export default Router;

应用程序.js:

import Route from './routing/route.js';
import Router from './routing/router.js';

(function () {
  function init() {
      var router = new Router([
          new Route('Category', 'Category.html', true),
          new Route('ActionSetA', 'ActionSetA.html'),
          new Route('ActionSetB', 'ActionSetB.html'),
          new Route('AnimalSetA', 'AnimalSetA.html'),
          new Route('AnimalSetB', 'AnimalSetB.html'),
          new Route('Clothes', 'Clothes.html'),
          new Route('Emotions', 'Emotions.html'),
      ]);
  }
  init();
}());

这是我的网络包:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: './src/app.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js'
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: 'html-loader',
            options: { minimize: false },
          },
        ],
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
          },
          {
            loader: 'css-loader',
          },
          {
            loader: 'sass-loader',
          },
        ],
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: 'images',
              name: '[name].[ext]',
            },
          },
          {
            loader: 'image-webpack-loader',
            options: {
              bypassOnDebug : true,
              mozjpeg: {
                progressive: true,
                quality: 75
              },
              optipng: {
                enabled: false,
              },
              pngquant: {
                quality: [0.65, 0.90],
                speed: 4
              },
              gifsicle: {
                interlaced: false,
                optimizationLevel: 1
              },
              webp: {
                quality: 75
              }
            }
          }
        ],
      },
      {
        test: /\.(woff|woff2|ttf|otf|eot)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: 'fonts',
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new  HtmlWebPackPlugin({
      template: './src/index.html',
      filename: './index.html'
    }),
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[id].css',
    }),
    new CopyWebpackPlugin([
      {from: './src/images', to: './images'},
    ]),
  ],
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    port: 3000,
  },
};

标签: javascriptdomsingle-page-application

解决方案


相对于您的服务器,您的路径似乎是错误的 http://localhost:3000/views/Category.html。

您的服务器正在运行的根路径可能是一些错误配置。

除此之外,很难猜出确切的错误。查看来自服务器的相对路径,检查您的服务器/webpack 配置。

更新:发布您的 webpack 更新,您能否检查您的“dist”文件夹是否具有正确的视图文件夹/路径,因为我认为您的 webpack 正在捆绑并将您的文件部署到“dist”文件夹。


推荐阅读