Variances in errors observed while accessing a website on ports 80 and 5500

I've been developing a chatbot system, and I'm encountering an issue where I receive an error message every time I send a message and expect a response back.

What's puzzling is that the error message varies depending on whether I run the site on localhost port 80 or 5500. Additionally, running it on localhost:5500 doesn't require an Apache server, whereas port 80 (localhost) does.

If I run it on localhost (port 80), I encounter:

POST http://localhost/get-response/ 404 (Not Found)

On the other hand, if I run it on localhost:5500, I see:

POST http://localhost:5500/get-response/ 405 (Method Not Allowed)

In my code snippet chatbot.js, there appears to be an error causing this issue:

            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'])
                    })

Furthermore, in urls.py and views.py, the routing and handling of the POST request are configured as follows:

urlpatterns = [
    url('', Index),
    path('get-response/', get_response),
]
@csrf_exempt
def get_response(request):
    # Code for handling the POST request

If I run into errors with the post data, how do I determine which specific error message to troubleshoot?

Answer №1

To use a function as an API view, make sure to include it in the method decorator as shown below:

 from rest_framework.decorators import api_view
 @csrf_exempt
 @api_view(['POST'])
 def get_response(request):
      .....
    your code
      .....

This should help you find a solution to your problem.

If you need to use more than one HTTP method, you can specify them like this:

@api_view(['POST', 'GET'])

Additionally, if you want to run the server on port 80, include it in the command like so:

 python manage.py runserver 127.0.0.1:80

Remember, 127.0.0.1 refers to localhost and the default port number for `python manage.py runserver` is 8000.

Answer №2

To implement API methods in your view, make sure to follow the example below:

from rest_framework.decorators import api_view

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

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

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

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach to implementing a filter in Vue 2 that is also compatible with Vue 3?

Currently, I am utilizing Vue.js 2+ version and have implemented a date formatting filter to meet my needs. However, I recently found out that Vue 3 has removed the filter functionality in favor of using computed properties or methods. My dilemma now is ho ...

Can a faulty image be cached?

Is there a way to ensure that the browser caches invalid or broken images so that when they are re-fetched, the loading time is immediate? I am particularly interested in two scenarios: 1) The first scenario involves trying to load an image from a URL co ...

"Troubleshooting a blank page issue in Angular UI Router caused by query string

I've been struggling with an issue related to query string parameters for quite some time. When I navigate to /, everything works perfectly fine. However, if I try something like /?anything, it simply doesn't work. These are the configurations in ...

Accessing Row Data from a Material Table using a Button Click, Not through Row Selection

My React component features a material table view, shown here: https://i.stack.imgur.com/OUVOD.png Whenever the delete icon is clicked in the table, I want to access the rowdata associated with that particular row. However, all I am able to retrieve is ...

Show the current server time on the client side using Meteor

Is there a more efficient way to display the server's time as a running clock (h:m:s) on the client using Meteor? Traditional JavaScript/PHP methods involve fetching the server time periodically and calculating the time difference with the client. Bu ...

Toggle visibility of table row upon user click (HTML/JQuery)

Having an issue with showing or hiding table rows using jQuery. I would like it so that when a user clicks on a table row with id="jobtitle", the corresponding tr with class="texter" will either show up or hide if it is already displayed. This is my curre ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

Sending a PDF document to a function that specifically calls for a file location or URL

Currently, I am developing a web application for an online library where I need to extract metadata from PDF files that are uploaded. To achieve this, I am utilizing the nodejs libraries pdf.js-extract and multer-gridfs-storage for file uploads. However, I ...

Using jQuery cookies to dynamically change the body id during page loading

Is it possible to dynamically change the body ID during page load? I recently created an application that successfully changes the body ID. Now, I'm interested in detecting the body ID that I have already selected during page loading. Below is the c ...

Is there a way for me to link my script for use in a Detail.cshtml file?

I have added the following script to my _Layout.cshtml shared master view: <script src="@Url.Script("~/Scripts/PromptToSave.js")" type="text/javascript"></script> Is there a way to include this script in a Details or index page that does not ...

Generating a clickable link for a variable within javascript

$scope.msg = "Data Updated Successfully. Item ID: " + $scope.id; After successfully updating any data, a message will be displayed as "Data Updated Successfully. Item ID: 13456". I want to turn the ID into a clickable hyperlink. Here is what I have attem ...

Perform a Rails Ajax request to update a like or dislike status

Is there a way to implement like/dislike functionality in my RoR application using Ajax requests? I have integer values for both like and dislike counters. How can I use Ajax requests to increment either the "like" or "dislike" counter in my methods? In ...

Switching Between HTML Using Javascript

I am currently working on an app that allows users to easily check the local weather and temperature in either celsius or fahrenheit. However, I've encountered a problem when trying to switch between the two unit types by simply clicking on the temper ...

Horizontal Accordion Design for Cascading Style Sheets (CSS) Books

I am currently working on developing a page that features a book layout. This page will include tabs that users can expand individually. If you would like to see a working example, you can check out this link: https://codesandbox.io/s/book-layout-l28gh?fi ...

Strange behavior in Angular controllers

There's a timeframe control in my app that allows users to adjust a value displayed in months. You can use the right arrow to increase the value (e.g., January -> February), the left arrow to decrease it, or manually input a different month. Howev ...

Struggling to make JQuery AJAX POST function properly on my WampServer localhost

My current project involves developing a WordPress website locally using WampServer. In the process, I have created a custom js file named custom-js.js, which is located at C:\wamp64\www\wordpress\wp-content\themes\my-theme&bs ...

Efficiently transmitting WebSockets events/messages to multiple controllers in AngularJS

Incorporating AngularJs, I created a factory to manage a WebSocket connection effectively. Here is the code: .factory('WebSocketConnection', function () { var service = {}; service.callbacks = []; service.connect = func ...

What is the best way to loop through all the configurations in Django?

Is there a way to loop through all Django settings? I want to access settings that start with MYAPP_. I attempted the following method: from django.conf import settings for setting in settings: print(setting) However, this resulted in an exception: ...

What is the best way to extract a nested array of objects and merge them into the main array?

I've been working on a feature that involves grouping and ungrouping items. A few days ago, I posted this question: How can I group specific items within an object in the same array and delete them from the core array? where some helpful individuals ...

`Angular2 - exploring the complexities of function scope`

I'm facing a challenge while working on my Angular2 Sample with the http module. Here is a snippet from my component: app.loginComponent = ng.core.Component({ selector: 'login', templateUrl: 'app/login/login.html&ap ...