首页 > 解决方案 > 在 Heroku 上部署 Django rest-Vue 项目时出现错误 500

问题描述

我能够将我的第一个项目部署到heroku。API 是 this: https://segmentacion-app.herokuapp.com/cluster/,前面是 this: https://cluster-app-wedo.herokuapp.com/,当我尝试使用 api 时出现问题,我收到 this: Failed to load resource: the server responded with a status of 500 (Internal Server Error) Error: Request failed with status code 500 at t.exports (createError.js:16) at t.exports (settle.js:17) at XMLHttpRequest.p.onreadystatechange (xhr.js:61) Home.vue:598,我可以对我错过的内容进行一些反馈吗?

主页.vue

let datos = await axios.post('https://segmentacion-app.herokuapp.com/cluster/',json)
           .then(response => { ...

服务器.js

const express = require('express');
const port = process.env.PORT || 8080;
const app = express();

app.use(express.static(__dirname + '/dist/'));
app.get(/.*/, function(req, res) {
    res.sendfile(__dirname + '/dist/index.html');
});
app.listen(port);

console.log("Server started...");

设置.py

import os
import django_heroku

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


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

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

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

ALLOWED_HOSTS = ['https://cluster-app-wedo.herokuapp.com/',]


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'MiApp',
    'import_export',
    'django_extensions',
    'rest_framework',
    'api',
    'corsheaders',
]

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',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

CORS_ALLOWED_ORIGINS = [
    'http://localhost:8080',
    'https://cluster-app-wedo.herokuapp.com',
]

ROOT_URLCONF = 'ClusterApp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        '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 = 'ClusterApp.wsgi.application'


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

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

DATA_UPLOAD_MAX_NUMBER_FIELDS = None

# Password validation
# https://docs.djangoproject.com/en/3.0/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/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = False


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

STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

# esto desactiva el error de sync to async
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"

#esto es heroku
django_heroku.settings(locals())

标签: djangovue.jsherokudjango-rest-framework

解决方案


问题已server.js存档,现在是:

const express = require('express');
const path = require('path');
const serveStatic = require('serve-static');

app = express();
app.use(serveStatic(path.join(__dirname, 'dist')));
app.get(/.*/, function(req, res) {
    res.sendfile(__dirname + '/dist/index.html');
});

const port = process.env.PORT || 8080;
app.listen(port);

console.log("Server started..." + port);

另一件重要的事情是将服务器设置为生产:

heroku config:set NODE_ENV=production --app <YOUR-PROJECT-NAME-HERE>

我按照以下说明操作: https ://medium.com/netscape/deploying-a-vue-js-2-x-app-to-heroku-in-5-steps-tutorial-a69845ace489


推荐阅读