Синтаксическая ошибка при использовании поиска в Javascript

Я делаю формы на Django и JavaScript

Мне нужно отобразить форму после нажатия на кнопку, на которую будет дан ответ, и она вернет (в формате JSON) список с ответами.

Мой код index.js

document.querySelector("#create-blank-form").addEventListener("click", () => {
    const csrf = Cookies.get('csrftoken');
    fetch('/form/create', {
        method: "POST",
        headers: {'X-CSRFToken': csrf},
        body: JSON.stringify({
            title: "Untitled Form"
        })
    })
    .then(response =>  response.json())
    .then(result => {
        window.location = `/form/${result.code}/edit`
    })
})

Ошибка, ошибка указывает на .then(result...)

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Promise.then (async)        
(anonymous)

Мой views.py

def create_form(request):
print('hi')
# Creator must be authenticated
# Create a blank form API
if request.method == "POST":
    print('hi')
    data = json.loads(request.body)
    title = data["title"]
    code = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(30))
    choices = Choices(choice = "Option 1")
    choices.save()
    question = Questions(question_type = "multiple choice", question= "Untitled Question", required= False)
    question.save()
    question.choices.add(choices)
    question.save()
    form = Form(code = code, title = title, creator=request.user)
    form.save()
    form.questions.add(question)
    form.save()
    return JsonResponse({"message": "Sucess", "code": code})

Мой .html

<div class="form-template-box">
            <img src = "{% static 'Icon/blank-form.png' %}" alt = "Blank form" title = "Blank form" id="create-blank-form">
            <span class="form-template-label">Blank Form</span>
        </div>

my urls.py

path('form/create', views.create_form, name="create_form"),

Ошибка SyntaxError: Unexpected token < in JSON at position 0 говорит, что первый символ ответа - '<', и предполагает, что ответ дан в формате XML, а не JSON.

Так что response.json() не работает, потому что response не является правильным JSON. Если бы это было так, первым символом был бы '{' или '['.

Я бы предложил вам console.log() ответ, чтобы проверить его формат, а затем извлечь элемент 'code', который вы ищете, используя:

const parser = new DOMParser();
const doc = parser.parseFromString(response, 'text/xml');
const codeYouWant = doc.getElementsByTagName("code")[0].innerHTML;

Я думаю, что ваша функция имеет некоторые проблемы, которые возвращают ошибку вместо JSON Response. Поэтому в .then(response => response.json()) будет возникать ошибка. Вы можете попробовать пример ниже, чтобы проверить ошибку.

if request.method == "POST":
    try:
        print('hi')
        data = json.loads(request.body)
        title = data["title"]
        code = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(30))
        choices = Choices(choice = "Option 1")
        choices.save()
        question = Questions(question_type = "multiple choice", question= "Untitled Question", required= False)
        question.save()
        question.choices.add(choices)
        question.save()
        form = Form(code = code, title = title, creator=request.user)
        form.save()
        form.questions.add(question)
        form.save()
        return JsonResponse({"message": "Sucess", "code": code})
    except Exception as err:
        return JsonResponse({"message": "Failed", "error": err})

И

.then(result => {
        console.log("DEBUG result: ", result);
        window.location = `/form/${result.code}/edit`
    })

моя проблема была с url, в urls.py, другая часть моего кода почему-то влияла не так как надо. спасибо за комментарии, они помогли мне найти ошибку

Вернуться на верх