【发布时间】:2023-01-25 04:32:59
【问题描述】:
所以我正在尝试学习 Vue,并且我已经建立了一个项目和一个 json-server 后端,它们都使用 Docker 运行。几乎一切都按预期工作。 我写了一个函数来获取 json 后端中的任务:
async fetchTasks(){
const res = await fetch('api/tasks')
const data = await res.json()
return data
}
当我尝试获取任务时:
async created(){
this.tasks = await this.fetchTasks()
}
我在浏览器控制台上收到以下错误:
GET http://localhost:8080/api/tasks 500 (Internal Server Error)
我也在运行容器的终端上得到这个:
task-tracker | 6:46:11 PM [vite] http proxy error:
task-tracker | Error: connect ECONNREFUSED 127.0.0.1:5000
task-tracker | at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1278:16)
但是,如果我将功能更改为:
async fetchTasks(){
const res = await fetch('http://localhost:5000/tasks') //hardcoded localhost
const data = await res.json()
return data
}
一切正常。
使用浏览器手动访问 localhost:5000/tasks 也可以。它显示了 db.json 的内容。
改变目标到jsonplaceholder.typicode.com也有效但这不是我想要的数据。
我究竟做错了什么?
这是我的 vite 配置:
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
proxy: {
'/api': {
target: 'http://127.0.0.1:5000',
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})
db.json(后端):
{
"tasks": [
{
"id": "1",
"text": "Doctors appointment",
"day": "March 1st at 2:30 pm",
"reminder": true
},
{
"id": 2,
"text": "Meeting at school",
"day": "March 3rd at 1:30 pm",
"reminder": true
},
{
"id": 3,
"text": "Food Shopping",
"day": "March 3rd at 11:00 am pm",
"reminder": false
}
]
}
docker-compose.yml:
services:
task-tracker:
image: "node:16"
container_name: "task-tracker"
user: "node"
working_dir: "/usr/src/app"
environment:
- NODE_ENV=development
volumes:
- ./:/usr/src/app
ports:
- "8080:8080"
command: "npm run dev -- --port 8080"
task-tracker-db:
image: "clue/json-server" #https://github.com/clue/docker-json-server
container_name: "task-tracker-db"
working_dir: "/data"
environment:
- NODE_ENV=development
volumes:
- ./db:/data
ports:
- "5000:80" #has to be 80 because the image exposes port 80
我试过了:
- 关注the documentation。
- 设置ws选择权真的.
- 使用以下代码进行配置:
module.exports = {
devServer: {
proxy: {
'^/api': {
target: 'http://localhost:5000',
changeOrigin: true,
logLevel: 'debug',
pathRewrite: {'^/api': '/'}
}
}
}
}
- 改变服务器到开发服务器
- 使用正则表达式
- 改变任务跟踪器数据库主机端口docker-compose.yml
- 改变127.0.0.1:5000到本地主机:5000
【问题讨论】:
标签: docker proxy vuejs3 vite json-server