Could there be a potential explanation for a 400 error in spite of successful testing in Post

I am currently experiencing an issue with the Deepl API. When I make a request using Postman, it is successful. However, when trying to use it in my app, I only receive a 400 Error response. I suspect that this may be due to incorrect headers setup, even though they match what I have in Postman. Can anyone help me identify what might be causing this problem?

async translateMessage(data = {}) {
  const url = "https://api.deepl.com/v2/translate?auth_key=myAuthKey";
  const response = await fetch(url, {
    method: "POST",
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': '*/*'
    },
    body: {
      text: JSON.stringify(this.text),
      target_lang: 'DE',
      source_lang: 'EN'
    }
  });
  return response.json();
},

You can refer to an example HTTP Post Request from the Documentation here.

POST /v2/translate?auth_key=[yourAuthKey]> HTTP/1.0
Host: api.deepl.com
User-Agent: YourApp
Accept: */*
Content-Length: [length]
Content-Type: application/x-www-form-urlencoded

auth_key=[yourAuthKey]&text=Hello, world&source_lang=EN&target_lang=DE

Answer №1

When dealing with a URL-encoded message that has the content type of

application/x-www-form-urlencoded
, it is crucial for the body property to consist either of a string containing the query parameters or an instance of URLSearchParams.

Resolution

  1. Utilize the key/value pairs object when invoking the URLSearchParams constructor.
  2. Ensure to include the auth_key (one of the mandatory query parameters) within the object and eliminate it from the URL.
  3. Omit the use of JSON.stringify() on the text property in order to prevent unnecessary quotation marks in the translation.
const url = 'https://api.deepl.com/v2/translate';
const response = await fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': '*/*'
  },
  body: new URLSearchParams({
    auth_key: myAuthKey,
    text: this.text,
    target_lang: 'DE',
    source_lang: 'EN'
  })
});

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 it about Next JS and React JS applications that causes them to use up so much cache?

"What causes Next.js and React.js applications to need a large cache, and how does this affect their performance and resource usage?" Refreshing constantly for even small changes in the application as a developer can be frustrating. Are there an ...

Removing quotes from JSON values in Node.js without removing quotes from JSON keys

For my project, I am currently developing a REST API that utilizes a library called JSONata for data transformation. The API is designed to receive JSON input consisting of both data and mapping information. Below is a simple example: { "map":{ ...

When navigating back, the Bootstrap Multistep Form breaks down

Tools I'm currently utilizing: HTML, CSS, Javascript, Bootstrap 3 Library / Package in use: https://codepen.io/designify-me/pen/qrJWpG Hello there! I am attempting to customize a Codepen-based Bootstrap Multistep Form from the provided link abov ...

Modeling a versatile user system in Mongoose for various user types

I am in the process of creating a unique social networking platform for students and teachers using the MEAN stack. Each student will have their own distinct account page separate from the teachers. There is only one registration page where both teachers ...

Successfully resolved: Inability to dynamically adjust button color according to its state

Currently I am working on a feature where a button changes color when it is disabled, but also has a custom color when enabled. Here is the code snippet I am using: Despite setting blue text for the button, it remains blue even after becoming disabled. Ho ...

Creating a unique attribute in FabricJS object using TypeScript

Encountering a TypeScript error when trying to add a custom attribute to a new FabricJS object. How can I extend the IObjectOptions globally to include this custom attribute? const workarea = new fabric.Rect({ id: "workarea", width: 250, he ...

How can I make Requirejs and Threejs OrbitControls work together?

Having trouble implementing OrbitControls with requirejs. Here's my configuration: I attempted to follow guidance from this post on Stack Overflow RequireJS and THREE.js Orbit Controls, but it's not working. requirejs.config({ baseUrl: &ap ...

Glitch in Mean App: front-end feature malfunctioning during data storage in mongodb

I am encountering difficulties while working on a MEAN app. I attempted to establish a connection between the backend (Node.js, Express.js) and the frontend (Angular 6), but encountered some issues. The backend port is http://localhost:3000, and the fron ...

JavaScript - Attempting to insert a value into a text field by clicking a button

I am struggling to get my function to properly add the value of the button to the text field when clicked by the user. HTML <form name="testing" action="test.php" method="get">Chords: <textarea name="field"& ...

The ngOnInit function is not triggered upon instantiation of an Injectable class

What could be causing the ngOnInit() method not to be called upon resolution of an Injectable class? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable ...

What is the best way to automate sending emails for every error that arises in Node.js?

In the scenario where my node.js application is up and running, I am looking for a way to handle all types of errors (not just web errors) and have a function that can send an email notification when an error occurs. Essentially, before the error gets wr ...

Is it possible to utilize jQuery's .wrap or .wrapInner to encase a variety of elements within them?

I am working with a HTML structure that looks like this: <section> <item> <ele class="blue" /> <ele class="green" /> <ele class="red" /> </item> <item> <ele class="blue" /> <ele ...

Iterate over JSON dates in JavaScript

Trying to utilize JavaScript in looping through a JSON file containing time periods (start date/time and end date/time) to determine if the current date/time falls within any of these periods. The provided code doesn't seem to be working as expected. ...

ES6 syntax specification allows for the use of a fat arrow function for declaring React components

When learning React, I have noticed two different ways of declaring components. The first is using the classic fat arrow syntax with a return statement. const Component = () => { return ( <div>Hello</div> ) } Recently, I came ...

"Send the response in ExpressJS before making a request to loop through the

I am currently working with a postgres database that contains records with a column format in JSON, which refers to other similar records. The challenge I am facing is retrieving linked records through asynchronous methods due to the nested structure and ...

Steps for utilizing Bazel to compile TypeScript

Calling all Bazel (Blaze) experts: I'm curious about the best method for integrating Bazel as a build system for cutting-edge web applications built in Typescript. Is there a preferred setup or perhaps a template that demonstrates this integration? T ...

What is the reason behind JavaScript objects lacking a toJSON() method?

According to information from http://www.json.org/js.html, JavaScript objects can specify how they are serialized by JSON.stringify() through the use of a toJSON() method. It is interesting to note that numbers and strings appear to have this method, but f ...

Employ Mustache.js for displaying a series of data points retrieved from a JSON reply

Utilizing Mustache.js to format the response from a jQuery getJSON() request has been quite helpful. The getJSON request is responsible for obtaining a list of image names, which I plan to display at the end of my content once the call is made. The JSON d ...

Variable scope fails to update upon selection change

I'm currently setting up a select dropdown with an ng-options. The dropdown is appearing correctly on the HTML page, but for some reason, when I choose an option, the variable specified by ng-model is not updating in $scope. This is the HTML code: &l ...

Problem with $http.post() in Angular where Codeigniter is not able to receive data

I'm facing a peculiar issue with Codeigniter and Angular. My approach was to configure the controller in the following way: index is a simple Angular page with just one app and one controller get retrieves data from the database set saves data sent u ...