我试图使开发环境正常工作,以使Vue应用程序(使用vue cli创建)在一个docker compose服务中,而django应用程序在另一个compose服务中运行。
调用特定网址(在django容器中)应返回vue应用。这是为了模仿当特定的Django URL返回包含vue构建的模板响应时它将如何在生产中工作。但是,在开发中,创建vue构建并在每次更改后复制文件都是不切实际的。
我正在遵循here中描述的方法。
我的撰写文件:
version: '3.6'
services:
db:
image: postgres:11.3
volumes:
- postgres_data:/var/lib/postgresql/data/
spa:
build:
context: .
dockerfile: ./Dockerfile-spa
image: site-spa
command: npm run serve
ports:
- 8080:8080
volumes:
- ./spa:/code
- /code/node_modules
- spa-files:/code
depends_on:
- db
backend:
build: .
image: site-backend
command: python ./manage.py runserver 0.0.0.0:8000
volumes:
- ./backend:/code
- spa-files:/code/spa
env_file:
- ./.envs/.dev/.backend
ports:
- 8000:8000
depends_on:
- db
- spa
volumes:
postgres_data:
spa-files:
我的vue.config.js
文件:
module.exports = {
devServer: {
disableHostCheck: true
}
}
我的django视图应返回vue spa(根据上面的链接文章):
def catchall(request, upstream="http://spa:8080"):
upstream_url = upstream + request.path
method = request.META["REQUEST_METHOD"].lower()
response = getattr(requests, method)(upstream_url, stream=True)
content_type = response.headers.get("Content-Type")
if request.META.get("HTTP_UPGRADE", "").lower() == "websocket":
return http.HttpResponse(
content="WebSocket connections aren't supported",
status=501,
reason="Not Implemented",
)
elif content_type == "text/html; charset=UTF-8":
return http.HttpResponse(
content=engines["django"].from_string(response.text).render(),
status=response.status_code,
reason=response.reason,
)
else:
return http.StreamingHttpResponse(
streaming_content=response.iter_content(2 ** 12),
content_type=content_type,
status=response.status_code,
reason=response.reason,
)
当我在django应用程序中浏览至spa网址时,出现以下浏览器错误:
GET http://localhost:8000/app.js net::ERR_ABORTED 404 (Not Found)
如果我在浏览器中查看页面源,则显示的是来自vue应用程序的index.html
页面。因此,该部分似乎正在工作。但是找不到app.js
。
我正在两个撰写服务之间共享spa文件。因此,我尝试将以下内容添加到Django设置中,以便它可以找到app.js:
FRONTEND_DIR = os.path.abspath(os.path.join(BASE_DIR, "..", "spa"))
STATICFILES_DIRS = [os.path.join(FRONTEND_DIR, "dist")]
只需澄清一下,问题不在于vue调用django api端点。这与django在开发中为vue应用提供服务有关。