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

请求Django接口出现404错误,URL变量未正确替换求助

解决Django API 404 NOT FOUND错误

错误现象

控制台返回404,请求URL如下:

GET http://127.0.0.1:8000/api/v1/products/$%7Bcategory_slug%7D/$%7Bproduct_slug%7D 404 (Not Found)

其中$%7Bcategory_slug%7D和$%7Bproduct_slug%7D是URL编码后的模板占位符,说明前端没有将变量替换为实际值就发送了请求。

解决方案

1. 修复前端API请求的模板字符串使用

在Product.vue组件中构造请求时,必须用**反引号`**包裹URL模板,同时从路由中正确获取参数:

// Product.vue 中的请求逻辑示例
import axios from 'axios'

export default {
  mounted() {
    // 从Vue路由中提取参数
    const { category_slug, product_slug } = this.$route.params
    // 使用反引号解析模板变量
    axios.get(`/api/v1/products/${category_slug}/${product_slug}/`)
      .then(res => {
        // 处理返回的产品数据
      })
      .catch(err => console.error(err))
  }
}

如果用单引号/双引号包裹URL,${变量}会被当作普通字符串,无法解析为实际参数值。

2. 验证Django主路由配置

确保项目根目录的urls.py已正确包含product子路由:

# 主项目 urls.py
from django.urls import path, include

urlpatterns = [
    # 其他路由...
    path('api/v1/', include('product.urls')),
]

只有这样,product/urls.py中的products/<slug:category_slug>/<slug:product_slug>/才能被正确映射到/api/v1/products/路径下。

3. 确认数据库存在对应数据

Django的ProductDetail视图会在找不到对应数据时抛出Http404,可以通过Django Shell验证数据是否存在:

# 运行 python manage.py shell
from product.models import Product
# 替换为实际的slug值
Product.objects.filter(category__slug='你的分类slug').get(slug='你的产品slug')

如果命令抛出Product.DoesNotExist,说明数据库中没有匹配的记录,需要先添加对应数据。

4. 检查Vue路由参数传递

跳转到Product路由时,要确保动态参数正确传递:

<!-- 产品列表页的跳转链接示例 -->
<router-link 
  :to="{ 
    name: 'Product', 
    params: { 
      category_slug: item.category.slug, 
      product_slug: item.slug 
    } 
  }"
>
  {{ item.name }}
</router-link>

必须使用:to(动态绑定)传递参数,不能用静态字符串拼接URL。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:30:49