Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
How can I convert a Dart POST request to JavaScript?

As I said, I want to convert that POST request with a file to JavaScript. This code sends a JSON request which contains an image file to server.

The Dart function is this (convert this to javascript):

Future postData(User user, VideoGame videoGame, File file) async {

    Map data = {
      'name': user.name,
      'contact': user.contact,
      'location': {
        'country': user.country,
        'state': user.state,
        'city': user.city
      },
      'videoGame': {
        'name': videoGame.name,
        'type': videoGame.type,
        'console': videoGame.console,
      }
    };

    try {

      String _url = baseUrl + 'insertData';

      var uri = Uri.parse(_url);
      var request = http.MultipartRequest('POST', uri)
        ..headers.addAll({'Content-type': 'multipart/form-data', 'Accept': 'multipart/form-data'}) 
        ..fields.addAll({'data': json.encode(data)});
      
      request.files.add(
        http.MultipartFile(
          'image',
          file.readAsBytes().asStream(),
          file.lengthSync(),
          filename: file.path.split("/").last
        ),
      );
      
      var response = await request.send();
      
      print('Status ${response.statusCode}');

      if (response.statusCode == 200) {
        final respStr = await response.stream.bytesToString();
        print(jsonDecode(respStr));

        MyALertKey
            .currentState
            ?.setState((){});
      }
    } catch (e) {
      print("Video Games POST error => ${e.toString()}");
    }
  }

Because the server written in Python I couldn't see that this file sends to server (request full body).

I have written this in JavaScript but it doesn't work.

const handleSubmit = async (e) => {
    e.preventDefault();

    var data = new FormData()

    var blob = new Blob([JSON.stringify({
      name: somevalue,
      contact: somevalue,
      location: {
        country: somevalue,
        state: somevalue,
        city: somevalue
      },
      videoGame: {
        name: somevalue,
        type: somevalue,
        console: somevalue,
      }
    })],{
      type: 'application/json'
    })

    data.append('data',blob)

    data.append('image',file_from_input)


    try {
      const res = await fetch('url',{
        method:'POST',
        cache: 'default',
        mode: 'no-cors',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        body: data
      })
      let data_ = await res.json()
      console.log(data_)
    } catch (e) {
      console.log(e)
    }

    console.log(res.status) // will be 400 bad request

  }

Please help me. Thanks.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda