JayK23
JayK23

Reputation: 253

ERR_ABORTED 404 (Not Found) error in VueJS

I deployed a Django+VueJS application to a Digital Ocean droplet using Nginx, the Django app is working but i can't see the VueJS components loaded by Webpack (i'm using Django-Webpack-Loader).

In my console, i keep seing these errors:

GET http://MYURL/static/vue/js/stopwatch.js net::ERR_ABORTED 404 (Not Found)
GET http://MYURL/static/vue/js/index.js net::ERR_ABORTED 404 (Not Found)

Which means that the static folder was not found. I made sure to use npm run build and manage.py collectstatic and i can see that the static folder is there, even though the app doesn't see it. Here is the path:

django-vue-mpa
   |-vue_frontend
   |-django_vue_mpa
     |-static

The full code of the application is here (i just cloned that repository and tried to deploy it).

Here is my vue.config.js (i think the problem might be here):

const BundleTracker = require("webpack-bundle-tracker");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;


const pages = {
    "stopwatch": {
        entry: "./src/stopwatch.js",
        chunks: ["chunk-moment", "chunk-vendors"],
    },
    "index": {
        entry: "./src/index.js",
        chunks: ["chunk-vendors"],
    },
    'vue_app_01': {
        entry: './src/main.js',
        chunks: ['chunk-vendors']
    },
    'vue_app_02': {
        entry: './src/newhampshir.js',
        chunks: ['chunk-vendors']
    },
}

module.exports = {
    pages: pages,
    filenameHashing: false,
    productionSourceMap: false,
    publicPath: process.env.NODE_ENV === 'production'
        ? '/static/vue'
        : 'http://localhost:8080/',
    outputDir: '/django-vue-mpa/django_vue_mpa/static/vue/',

    chainWebpack: config => {

        config.optimization
            .splitChunks({
                cacheGroups: {
                    moment: {
                        test: /[\\/]node_modules[\\/]moment/,
                        name: "chunk-moment",
                        chunks: "all",
                        priority: 5
                    },
                    vendor: {
                        test: /[\\/]node_modules[\\/]/,
                        name: "chunk-vendors",
                        chunks: "all",
                        priority: 1
                    },
                },
            });

        Object.keys(pages).forEach(page => {
            config.plugins.delete(`html-${page}`);
            config.plugins.delete(`preload-${page}`);
            config.plugins.delete(`prefetch-${page}`);
        })

        config
            .plugin('BundleTracker')
            .use(BundleTracker, [{filename: '../vue_frontend/webpack-stats.json'}]);

        // Uncomment below to analyze bundle sizes
        // config.plugin("BundleAnalyzerPlugin").use(BundleAnalyzerPlugin);
        
        config.resolve.alias
            .set('__STATIC__', 'static')

        config.devServer
            .public('http://localhost:8080')
            .host('localhost')
            .port(8080)
            .hotOnly(true)
            .watchOptions({poll: 1000})
            .https(false)
            .headers({"Access-Control-Allow-Origin": ["*"]})

    }
};

Here is my nginx config:

server {
    listen 80;
    server_name http://MYURL/;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /django-vue-mpa/django_vue_mpa/static;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/django-vue-mpa/django-vue-mpa.sock;
    }
}

And here is my settings.py:

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'MYKEY'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['MYURL']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'webpack_loader',
    'django_vue_mpa'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'django_vue_mpa.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'django_vue_mpa.wsgi.application'

VUE_FRONTEND_DIR = os.path.join(BASE_DIR, 'vue_frontend')

WEBPACK_LOADER = {
    'DEFAULT': {
        'CACHE': not DEBUG,
        'BUNDLE_DIR_NAME': 'vue/',  # must end with slash
        'STATS_FILE': os.path.join(VUE_FRONTEND_DIR, 'webpack-stats.json'),
        'POLL_INTERVAL': 0.3,
        'TIMEOUT': None,
        'IGNORE': [r'.+\.hot-update.js', r'.+\.map']
    }
}


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = "/django-vue-mpa/django_vue_mpa/static"

Upvotes: 0

Views: 5974

Answers (1)

Ivan Shatsky
Ivan Shatsky

Reputation: 15478

Check the difference between root and alias nginx directives. For your case you should use

location /static/ {
    root /django-vue-mpa/django_vue_mpa;
}

instead of

location /static/ {
    root /django-vue-mpa/django_vue_mpa/static;
}

You'd see nginx searches files on a wrong path if you looked at its error log.

Upvotes: 1

Related Questions