OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

400 Bad Request: Did not attempt to load JSON data because the request Content-Type was not 'application/json'

  • Thread starter Thread starter juanjo
  • Start date Start date
J

juanjo

Guest
I have the following problem, I am setting up an application in Vue and I have a component from which I must upload files to my gcp bucket, but when it comes to sending the upload request from my front to the back, it gives me the error of the title this is my front:

Code:
   <template>
      <div class="upload-container">
        <h4>Subida de Ficheros</h4>
        <b-form-file v-model="file" class="mt-3" plain></b-form-file>
        <button type="button" class="btn btn-primary" @click="uploadFile">Upload File</button>
        <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
        <p v-if="successMessage" class="success">{{ successMessage }}</p>
      </div>
    </template>
    <script>
    import { sp } from '@/utils/constants'
    export default {
      data () {
        return {
          file: null,
          errorMessage: null,
          successMessage: null
        }
      },
      methods: {
        async uploadFile () {
          if (!this.file) {
            this.errorMessage = 'Please select a file to upload.'
            return
          }
          this.errorMessage = null
          const formData = new FormData()
          formData.append('file', this.file)
          try {
            const response = await fetch(sp + 'upload_file', {
              method: 'POST',
              body: formData
            })
            if (!response.ok) {
              throw new Error(`Error: ${response.statusText}`)
            }
            const result = await response.json()
            this.successMessage = 'File uploaded successfully'
            console.log('Response from server:', result)
          } catch (error) {
            this.errorMessage = `Error uploading file: ${error.message}`
            console.error('Error uploading file:', error)
          }
        }
      }
    }
    </script>
    <style>
    .error {
      color: red;
    }
    .success {
      color: green;
    }
    </style>

Code:
@surveys_bp.route('/upload_file', methods=['POST'])
    def upload_file():
        try:
            logging.info('Handling upload file request')
            if 'file' not in request.files:
                logging.error('No file part in the request')
                return jsonify({'message': 'No file part in the request'}), 400
            file = request.files['file']
            if file.filename == '':
                logging.error('No selected file')
                return jsonify({'message': 'No selected file'}), 400
            filename = secure_filename(file.filename)
            logging.info(f'File received: {filename}')
            # Intentar subir el archivo a GCP
            try:
                upload_to_gcp(file, filename)
            except Exception as e:
                logging.error('Error uploading file to GCP', exc_info=True)
                return jsonify({'message': f'Error uploading file to GCP: {str(e)}'}), 500
            logging.info('File uploaded successfully')
            return jsonify({'message': 'File uploaded successfully'}), 200
        except Exception as e:
            logging.error('Error handling upload file request', exc_info=True)
            return jsonify({'message': str(e)}), 500
    
    
    def upload_to_gcp(file, filename):
        """Sube un archivo a Google Cloud Storage."""
        client = storage.Client()
        bucket = client.bucket('files_pending_processing')
        blob = bucket.blob(filename)
        file_content = file.read()
        blob.upload_from_string(file_content, content_type=file.mimetype)
        logging.info(f'File {filename} uploaded to GCP bucket.')

The call never enters the back process, but always returns the error mentioned in the title.

I have tried sending the request with axios and now with fetch and nothing, it always indicates the same message and I have also included the content/type many times in the headers and nothing.
<p>I have the following problem, I am setting up an application in Vue and I have a component from which I must upload files to my gcp bucket, but when it comes to sending the upload request from my front to the back, it gives me the error of the title
this is my front:</p>
<pre><code> <template>
<div class="upload-container">
<h4>Subida de Ficheros</h4>
<b-form-file v-model="file" class="mt-3" plain></b-form-file>
<button type="button" class="btn btn-primary" @click="uploadFile">Upload File</button>
<p v-if="errorMessage" class="error">{{ errorMessage }}</p>
<p v-if="successMessage" class="success">{{ successMessage }}</p>
</div>
</template>
<script>
import { sp } from '@/utils/constants'
export default {
data () {
return {
file: null,
errorMessage: null,
successMessage: null
}
},
methods: {
async uploadFile () {
if (!this.file) {
this.errorMessage = 'Please select a file to upload.'
return
}
this.errorMessage = null
const formData = new FormData()
formData.append('file', this.file)
try {
const response = await fetch(sp + 'upload_file', {
method: 'POST',
body: formData
})
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`)
}
const result = await response.json()
this.successMessage = 'File uploaded successfully'
console.log('Response from server:', result)
} catch (error) {
this.errorMessage = `Error uploading file: ${error.message}`
console.error('Error uploading file:', error)
}
}
}
}
</script>
<style>
.error {
color: red;
}
.success {
color: green;
}
</style>

</code></pre>
<pre><code>@surveys_bp.route('/upload_file', methods=['POST'])
def upload_file():
try:
logging.info('Handling upload file request')
if 'file' not in request.files:
logging.error('No file part in the request')
return jsonify({'message': 'No file part in the request'}), 400
file = request.files['file']
if file.filename == '':
logging.error('No selected file')
return jsonify({'message': 'No selected file'}), 400
filename = secure_filename(file.filename)
logging.info(f'File received: {filename}')
# Intentar subir el archivo a GCP
try:
upload_to_gcp(file, filename)
except Exception as e:
logging.error('Error uploading file to GCP', exc_info=True)
return jsonify({'message': f'Error uploading file to GCP: {str(e)}'}), 500
logging.info('File uploaded successfully')
return jsonify({'message': 'File uploaded successfully'}), 200
except Exception as e:
logging.error('Error handling upload file request', exc_info=True)
return jsonify({'message': str(e)}), 500


def upload_to_gcp(file, filename):
"""Sube un archivo a Google Cloud Storage."""
client = storage.Client()
bucket = client.bucket('files_pending_processing')
blob = bucket.blob(filename)
file_content = file.read()
blob.upload_from_string(file_content, content_type=file.mimetype)
logging.info(f'File {filename} uploaded to GCP bucket.')
</code></pre>
<p>The call never enters the back process, but always returns the error mentioned in the title.</p>
<p>I have tried sending the request with axios and now with fetch and nothing, it always indicates the same message and I have also included the content/type many times in the headers and nothing.</p>
 

Latest posts

Top