【发布时间】:2023-01-16 02:59:58
【问题描述】:
我正在设置一个 Astro 站点,该站点将显示从在同一主机但不同端口上运行的简单服务获取的数据。
该服务是一个简单的 Express 应用程序。
server.js:
const express = require('express')
const app = express()
const port = 3010
const response = {
message: "hello"
}
app.get('/api/all', (_req, res) => {
res.send(JSON.stringify(response))
})
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
由于该服务运行在与Astro站点不同的3010端口,因此我在Vite级别配置了一个server proxy。
astro.config.mjs:
import { defineConfig } from 'astro/config';
import react from '@astrojs/react';
export default defineConfig({
integrations: [react()],
vite: {
optimizeDeps: {
esbuildOptions: {
define: {
global: 'globalThis'
}
}
},
server: {
proxy: {
'/api/all': 'http://localhost:3010'
}
}
},
});
这是我尝试调用该服务的地方。
index.astro:
---
const response = await fetch('/api/all');
const data = await response.json();
console.log(data);
---
当我运行 yarn dev 时,我得到这个控制台输出:
Response {
size: 0,
[Symbol(Body internals)]: {
body: Readable {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
_read: [Function (anonymous)],
[Symbol(kCapture)]: false
},
stream: Readable {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
_read: [Function (anonymous)],
[Symbol(kCapture)]: false
},
boundary: null,
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
type: 'default',
url: undefined,
status: 404,
statusText: '',
headers: { date: 'Tue, 02 Aug 2022 19:41:02 GMT' },
counter: undefined,
highWaterMark: undefined
}
}
看起来网络请求正在返回 404。
我没有在 doc 中看到更多关于服务器配置的信息。 我这样做是对的吗?
我可以使用 vanilla Vite 应用程序和相同的配置/设置正常工作。
我如何代理 Astro 应用程序的本地服务调用?
【问题讨论】:
标签: node.js http-status-code-404 vite astrojs