简体   繁体   English

Django:获取 API 重定向到错误的 URL

[英]Django : Fetch API redirects to wrong URL

Im trying to send data to my django backend using javascript Fetch API.我正在尝试使用 javascript Fetch API 将数据发送到我的 django 后端。 My current working url is 127.0.0.1:8000/store我目前工作的 url 是127.0.0.1:8000/store

And im trying to send data to 127.0.0.1:8000/recommend_product/ using fetch as follows urls.py我正在尝试使用 fetch 将数据发送到127.0.0.1:8000/recommend_product/如下 urls.py

path('recommend_product/',product_utils.recommend_product,name = "recommend_product"),
 var url = '/recommend_product/'
            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrftoken,
                },
                body: JSON.stringify({ 'productId': productId })
            })
                .then((response) => {
                    return response.json()
                })

                .then((data) => {
                    console.log('data:', data)
                    location.reload()
                })
        } else {
            alert('Please Login to recommend products')
        }

My problem is that Fetch API redirecting me to '127.0.0.1:8000/store/recommend_product/' instead of 127.0.0.1:8000/recommend_product/ .我的问题是 Fetch API 将我重定向到'127.0.0.1:8000/store/recommend_product/'而不是127.0.0.1:8000/recommend_product/ How to fix this?如何解决这个问题?

I would guess it's something to do with how Django processes requests .我猜这与Django 处理 requests的方式有关。

Your url is only defined as var url = '/recommend_product/' , so it may be going to '127.0.0.1:8000/store/recommend_product/' by default if /store is your first defined url path. Your url is only defined as var url = '/recommend_product/' , so it may be going to '127.0.0.1:8000/store/recommend_product/' by default if /store is your first defined url path.

Edit: To correct it, be more specific with your url编辑:要更正它,请更具体地使用您的 url

var url = 'https://127.0.0.1:8000/recommend_product/'

Had the same problem.有同样的问题。 Although i dont think this is the best way, try http://127.0.0.1:8000/recommend_product虽然我认为这不是最好的方法,但请尝试http://127.0.0.1:8000/recommend_product

I had a similar error on my projects.我的项目也有类似的错误。 Your best bet might be to use javascript, as in ${window.location.host}/your_endpoint/ .您最好的选择可能是使用 javascript,如${window.location.host}/your_endpoint/ This would make it quite dynamic.这将使它非常动态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM