Неожиданный конец ввода JSON и 404 (не найдено) - PullRequest
0 голосов
/ 12 марта 2020

Я работаю над системой чат-ботов. Каждый раз, когда я пишу сообщение и ожидаю ответ, я получаю два сообщения об ошибке.

Uncaught (в обещании) SyntaxError: Неожиданный конец JSON input

Ошибка специально указывает на

.then(response => response.json()).then((json) => {

Я также получаю ошибка:

POST http://localhost/get-response/ 404 (не найдено)

, который указывает на fetch("/get-response/", {

Я прокомментировал это в коде ниже:

скрипт. js

window.onload = function () {
    var app = new Vue({
      delimiters: ['[[', ']]'],
      el: '#app',
      data: {
        messages: [],
        input: '',
        send_blank: false,
        placeholder: 'Send a message to the chatbot...',
      },
      created: function() {

      },
      methods: {
        add_message: function() {
            if (this.input.length > 0) {
                var message = {
                    'text': this.input,
                    'user': true,
                    'chat_bot': false,
                };
                this.messages.push(message);
                this.input = '';

                //just incase
                this.send_blank = false;
                this.placeholder = "Send a message to the chatbot...";

                fetch("/get-response/", { //<---- The 404 error points to this
                    body: JSON.stringify({'message': message['text']}),
                    cache: 'no-cache', 
                    credentials: 'same-origin', 
                    headers: {
                        'user-agent': 'Mozilla/4.0 MDN Example',
                        'content-type': 'application/json'
                    },
                    method: 'POST',
                    mode: 'cors', 
                    redirect: 'follow',
                    referrer: 'no-referrer',
                    })
                    .then(response => response.json()).then((json) => { //<--- The SyntaxError points to this
                        this.messages.push(json['message'])
                    })
            } else {
                this.send_blank = true;
                this.placeholder = "Please put in some text";
            }

        }

urls.py

from django.contrib import admin
from django.conf.urls import include, url
from django.urls import path
from MyApp.views import Index, get_response
from django.conf.urls.static import static
from django.conf import settings



urlpatterns = [
    url('', Index),
    path('get-response/', get_response),
]

Views.py

from django.shortcuts import render
from django.http import HttpResponse
import json
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view


from chatterbot import ChatBot

# Create your views here.
chatbot = ChatBot(
    'Ron Obvious',
    trainer='chatterbot.trainers.ChatterBotCorpusTrainer'
)

@csrf_exempt
@api_view(['POST'])
def get_response(request):
    response = {'status': None}

    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        message = data['message']

        chat_response = chatbot.get_response(message).text
        response['message'] = {'text': chat_response, 'user': False, 'chat_bot': True}
        response['status'] = 'ok'

    else:
        response['error'] = 'no post data found'

    return HttpResponse(
        json.dumps(response),
            content_type="application/json"
        )

def Index (request):
    context = {'title': 'Chatbot Version 1.0'}

    return render(request, "AI.html", context)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...