我正在使用聊天机器人系统。每次我写一条消息并希望返回一条消息时,都会收到一条错误消息。
奇怪的是,错误消息取决于我是在本地主机端口80还是5500上运行站点。另一件事是,本地主机:5500不需要Apache服务器,而端口80(本地主机)则需要。
如果我在本地主机(端口80)上运行,则会得到
POSThttp://localhost/get-response/404(未找到)
如果我在localhost:5500上运行,则会得到
POSThttp://localhost:5500/get-response/405(不允许使用方法)
chatbot.js
fetch("/get-response/", { //<--- error
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) => {
this.messages.push(json['message'])
})
urls.py
urlpatterns = [
url('', Index),
path('get-response/', get_response),
]
views.py
@csrf_exempt
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)
我怎么知道要发送哪个错误消息?
您正在使用函数作为API视图,因此应在如下所示的方法装饰器中提及
from rest_framework.decorators import api_view
@csrf_exempt
@api_view(['POST'])
def get_response(request):
.....
your code
.....
希望它会为您提供解决方案。
可以使用多个HTTP方法,如下所示。
@api_view(['POST', 'GET'])
如果要在端口80上运行服务器,则应在如下所示的命令中提及它。
python manage.py runserver 127.0.0.1:80
127.0.0.1表示本地主机
python manage.py runserver将使用端口号8000