You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express.js后端访问/api/weather返回unknown endpoint,API调用失败

Express API 返回 "unknown endpoint" 问题排查方案

1. 检查路由挂载顺序

Express 路由匹配是从上到下执行的,若404中间件挂载在业务路由之前,会优先触发"unknown endpoint"提示。

  • 务必保证app.js中,天气路由的挂载代码放在404中间件之前:
    // 先挂载业务路由
    app.use('/api/weather', weatherRouter)
    // 最后挂载404兜底中间件
    app.use((req, res) => {
      res.status(404).send("unknown endpoint")
    })
    

2. 验证路由定义正确性

检查天气路由文件的代码细节:

  • 确保使用GET方法匹配请求(前端发起的是带query参数的GET请求)
  • 路由内部不要重复加前缀,app.use('/api/weather')已经指定了前缀,路由内的/对应完整路径/api/weather:
    const express = require('express')
    const router = express.Router()
    const axios = require('axios')
    
    router.get('/', async (req, res) => {
      const city = req.query.city
      if (!city) return res.status(400).send("city参数必填")
      
      try {
        const apiKey = '你的OpenWeatherMap密钥'
        const resp = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`)
        res.json(resp.data)
      } catch (err) {
        res.status(500).send("获取天气数据失败")
      }
    })
    
    module.exports = router
    

3. 确认前端请求与代理配置

  • 前端请求需使用正确的路径,若配置了Vite代理,直接请求/api/weather即可:
    const fetchWeather = async (city) => {
      try {
        const resp = await fetch(`/api/weather?city=${encodeURIComponent(city)}`)
        const data = await resp.json()
        console.log(data)
      } catch (err) {
        console.error(err)
      }
    }
    
  • 检查vite.config.js的代理配置是否正确:
    export default defineConfig({
      server: {
        proxy: {
          '/api': {
            target: 'http://localhost:3004',
            changeOrigin: true
          }
        }
      }
    })
    

4. 直接测试后端API

绕开前端,用curl或Postman直接请求http://localhost:3004/api/weather?city=Beijing:

  • 若仍返回"unknown endpoint",问题在后端路由配置
  • 若能正常返回JSON,问题在前端请求或代理配置

5. 查看服务器请求日志

用morgan中间件开启请求日志,确认请求路径和方法是否匹配:

const morgan = require('morgan')
app.use(morgan('dev'))

终端会输出类似日志:GET /api/weather?city=Beijing 404 2.345 ms - 19,可直接判断请求路径是否被正确识别

内容的提问来源于stack exchange,提问作者t0v4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 15:55:58