Back

Technologies:

javascriptjavascript
htmlhtml
avatar
Tolerim
a month ago

Why does the "Unsupported Media Type" error appear in the HTML file, and what is the reason behind it?

I am currently attempting to develop an AI chatbot, however, upon clicking "send" in the inputs, I receive the following error: error. Additionally, I am encountering an error in the terminal that reads: "POST /procesar HTTP/1.1" 415 html. To provide more context, I have included relevant code snippets, including HTML, JavaScript, and Python. In order to address the issue at hand, I attempted to modify the problem by consulting ChatGPT, but have yet to find a solution. While I acknowledge that I am in the process of honing my coding skills, any assistance in resolving this matter would be greatly appreciated.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="static/css/stylesheet.css">
    <link rel="icon" href="icons/Logo.jpg">
    <title>StudentsGPT</title>
</head>
<body>
    <header class="top-bar">
        <a class="active" href="index.html">StudentsGPT</a>
        <a href="#about">About</a>
        <a href="#help">Help</a>
        <a href="#contact">Contact</a>
    </header>
    <div>
        <div class="response-style">
            <p id="outputprompt"></p>
        </div>
        <div class="input-style">
            <center>
                <input name="api" id="apiKey" type="text" placeholder="Type your API Key" required>
                <input name="input" id="inputPrompt" type="text" placeholder="Type your question" required>
                <button type="button" onclick="recibirPrompt()">Send</button>
            </center>
        </div>
    </div>
    <script src="static/js/script.js"></script>
</body>
</html>
function recibirPrompt(){
    var inputPrompt = document.getElementById("inputPrompt").ariaValue;
    var apiKey = document.getElementById("apiKey").ariaValue;
    fetch('/procesar', {
        method: 'POST',
        Headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            'Accept':'application/json'
        },
        body: JSON.stringify({api: apiKey, input: inputPrompt})
    })
    .then(response => response.text())
    .then(data =>{
        document.getElementById("outputprompt").innerHTML = data;
    });
}
from flask import Flask, request
import openai
import os
import json

app = Flask(name, staticurlpath='/static')

def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0,
        max_tokens=1000,
    )
    return response.choices[0].message["content"]

@app.route('/')
def index():
    with open('index.html', 'r') as file:
        return file.read()

@app.route('/procesar', methods=['POST'])
def procesar():
    data = request.json
    apiKey = data['api']
    openai.api_key = apiKey
    inputPrompt = data['input']
    prompt_1 = f"""
Perform the following action: 
- Summarize the following text delimited by triple backticks into steps in the same language as the text. If the text does not contain any discernible set of instructions, please respond with: "Please, introduce your problem again." (do not change the language on this answer).
Text:
```{inputPrompt}```
"""
    model="gpt-3.5-turbo"
    response1 = getcompletion(prompt1)
    if response1 == "Please, introduce your problem again.":
        finalAnswer = response1
        print(response1)
        return finalAnswer

    else:
        prompt_2 = f"""Calculate the result of the following actions delimited by triple backticks and show and explain the process like if you were a teacher (answer in the same language as the actions):
    Actions:
    ```{response1}```
    """
        response2 = getcompletion(prompt2)
        finalAnswer = response2
        return finalAnswer

if name == 'main':
    app.run(debug=True)
Answers(2)
avatar
Vogi
a month ago
Verified Answer
The error you are encountering is a 415 Unsupported Media Type error. This error occurs when the server refuses to accept the request because the payload format is in an unsupported format. The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method. In your code snippet, I noticed that you are sending a JSON object as the payload of your POST request. However, you have not specified that you are sending JSON data in your headers. You can fix this by adding 'Content-Type': 'application/json' to your headers. Here's an example of how you can modify your code snippet:
function recibirPrompt(){
    var inputPrompt = document.getElementById("inputPrompt").ariaValue;
    var apiKey = document.getElementById("apiKey").ariaValue;
    fetch('/procesar', {
        method: 'POST',
        Headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            'Accept':'application/json'
        },
        body: JSON.stringify({api: apiKey, input: inputPrompt})
    })
    .then(response =&gt; response.text())
    .then(data =&gt;{
        document.getElementById("outputprompt").innerHTML = data;
    });
}
I hope this helps! Let me know if you have any other questions.

Sources

No response from OpenAi using Flask - Stack OverflowError 415 Unsupported Media Type: POST not reaching REST if JSON, but ...Web API Post returns 415 - Unsupported Media TypeNewbie Haas TM-1 Post processor needed - cnczone.comopenai api - Streaming ChatGPT's results with Flask and LangChain ...Building a Chatbot with OpenAI's GPT-3 engine, Twilio SMS and Python
avatar
Tolerim
a month ago
The error "POST /procesar HTTP/1.1" 415 occurs when the media type of the request payload is not supported by the server. In this case, the server expects the data to be in JSON format, but the payload is not of that type. To fix this issue, you can modify the JavaScript function recibirPrompt() to set the correct Content-Type header in the request:
function recibirPrompt(){
    var inputPrompt = document.getElementById("inputPrompt").value;
    var apiKey = document.getElementById("apiKey").value;

    fetch('/procesar', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({api: apiKey, input: inputPrompt})
    })
    .then(response => response.text())
    .then(data =>{
        document.getElementById("outputprompt").innerHTML = data;
    });
}
In the above code, we have set the Content-Type header to application/json, and we have used the JSON.stringify() method to convert the payload to JSON format. Also, we have used the value property instead of ariaValue to get the value of the input elements.
;