'Express server returns empty string as a response for proxied requests in Vite
The request from frontend to backend is proxied successfully. The server fetches and logs the expected data. But the frontend logs empty string despite the backend returning the exact data logged.
Backend Code:
const app = express()
app.use(express.json())
app.listen(8000, () => console.log('working'))
app.get('/current', async (req, res) => {
const { lat, lon } = req.query
try {
const response = await axios.get(
`https://api.openweathermap.org/data/2.5/weather?units=metric&lat=${lat}&lon=${lon}&appid=${process.env.API_KEY}`
)
console.log(response.data) //logs expected data
res.json(response.data)
} catch (e) {
console.error(e)
res.json(e)
}
})
Frontend code:
const { data } = useSWRV(
() => `/api/current?lat=${lat}&lon=${lon}`,
async key => {
const res = await axios.get(key)
console.log(res.data) //logs empty string
return res.data
}
)
ViteConfig.ts
import vue from '@vitejs/plugin-vue'
import { fileURLToPath, URL } from 'url'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
server: {
proxy: {
'/api': {
forward: 'http://localhost:8000',
secure: false,
ws: true,
rewrite: path => path.replace('api', ''),
},
},
},
})
I tried sending a request to http://localhost:8000 directly without proxying which resulted in a CORS error (Missing allowed origin).
No error message is logged when using proxy.
Solution 1:[1]
Silly me. Changing forward: 'http://localhost:8000' to target: 'http://localhost:8000' solved the problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tenshi Munasinghe |
