Utilizing Forms in a Post Request (including JavaScript fetch())

How do I include a form parameter in a POST request using JavaScript fetch()? For example:

curl --form "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a5b4c5b4e5a5840787a51454b585d">[email protected]</a>" "https://example.com/api/v4/endpoint"

I attempted the following code:

const form = new FormData()
form.append("foo":"bar")
fetch( "https://someapi.org/api", {
    method: 'POST',
    headers: form
} )
    .then( response => response.json() )
    .then( response => {
        console.log(response)
    } );
}

This approach did not work for me.

Answer №1

Ensure that the FormData is included in the body property of the RequestInit as shown below:

Remember to set the appropriate Content-Type header. You can learn more about Using FormData Objects on MDN.

TS Playground

so-70865955.ts:

async function example () {
  const form = new FormData();
  form.append("foo", "bar");

  const apiAddress = "https://someapi.org/api";

  const init: RequestInit = {
    method: 'POST',
    headers: new Headers([['content-type', 'application/x-www-form-urlencoded']]),
    body: form,
  };

  const response = await fetch(apiAddress, init);
  const data = await response.json();
  console.log(data);
}

// Invoke it
example();

When running in your console, use the command:

deno run --allow-net so-70865955.ts

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

Guide on how to navigate within an app by clicking on a link from an email

Is there a way to launch my Android application (Nativescript) from a link in an email that says "Click here to reset password"? For example, the email contains a link like this: When I click on this link from my mobile browser, I want the app to open to ...

Is there a way to remove array elements once in order to replace them with new ones using a for loop?

My objective is to achieve the following: Assign an array value (list) to another array (options). If the user input (searchVal) matches a value in the list, remove existing options and add this match. Subsequently continue adding any additional matches w ...

Reduce brightness in JavaScript - adjust downward

I stumbled upon this code snippet on Stack Overflow: function increase_brightness(hex, percent){ var r = parseInt(hex.substr(1, 2), 16), g = parseInt(hex.substr(3, 2), 16), b = parseInt(hex.substr(5, 2), 16); return '#' ...

Obtain the values from this JSON array

o = { "photos": { "page": 1, "pages": 46, "perpage": 5, "total": "230", "photo": [{ "id": "6643924777", "owner": "34653895@N08", "secret": "3b7c2f6469", "server": " ...

Angular material is experiencing an issue where content is being cut off or

I am currently working on a project using AngularJS for a web application. I have encountered an issue where some of the content in the md-content element is being clipped. For instance, the body tag has the style: overflow: hidden, and the child md-conte ...

JavaScript: Finding the current month and all subsequent months until the end of the year

Is there a way in vanilla JavaScript to retrieve the current month and the following 12 months? For instance, if today is April 2022, I would like the output to be: April 2022 May 2022 June 2022 July 2022 August 2022 September 2022 October 2022 November 2 ...

TypeORM Error: Trying to access property 'findOne' of an undefined object

I've been working on implementing TypeORM with Typescript, and I have encountered an issue while trying to create a service that extends the TypeORM repository: export class UserService extends Repository<User> { // ... other service methods ...

Insert within a canvas

Although there is a previous inquiry on this topic, it appears to be outdated. Despite searching through dartlang's resources and conducting online research, I have yet to find a solution to the issue at hand. document.onPaste.listen((e) { ...

What is the correct method for specifying the date field in my TypeScript interface that will be retrieved from my cloud function?

Context: Utilizing Vue to interact with cloud functions for accessing data from firestore (avoiding direct firestore queries). A function is called wherein one field returns firestore's timestamp representation (seconds, nanoseconds). Also, I'm a ...

Using Javascript to Treat an HTML Document as a String

Check out the complete project on GitHub: https://github.com/sosophia10/TimeCapsule (refer to js/experience.js) I'm utilizing JQuery to develop "applications" for my website. I'm encountering a problem where I can't locate the correct synta ...

Trouble arises when attempting to compare two JSON files with an undefined issue

data-info.json {"price-comparison":[[{"Price":"0.0"},{"Code":"C0358102"}],[{"Price":"2.0"},{"Code":"C0876548"}]],"isEmployeeOJ":"Y"} script.js var dataInfo = $http.get("data/data-info.json").then(function (response) { $scope.dataInfo = response.data; ...

Create a jQuery popup form with a variety of interactive buttons

Is it possible to implement a modal form in jQuery that can be triggered by multiple buttons? All the buttons have identical names and IDs. The goal is to display the modal form whenever any button is clicked. For this example, let's consider having ...

This method or property is not supported by the object - How to call an Applet in Internet Explorer 9

cmd > java -version Java Version : "1.7.0_11" (Updated) Java(TM) SE Runtime Environment (build 1.7.0_11-b21) Java HotSpot(TM) Client VM (build 23.6-b04, mixed mode, sharing) browsers = IE7,IE8,IE9 (The functionality works smoothly in Google Chrome and ...

App:// is where Electron and Vue API requests converge

Recently, I successfully integrated Electron into my Vue app with the help of the Vue CLI Plugin Electron Builder. During development, all API requests were properly directed to the address specified in my vue.config.js: proxy: { '^/api': ...

Ways to effortlessly activate an angular directive once the page has been fully loaded

I am facing an issue with a print directive that is triggered by the print="id" attribute within an <a></a> element. The button is contained in a modal that remains hidden from the user. I want the directive to execute as soon as the modal is l ...

Limitations on Embedding Videos with YouTube Data API

I have been using the Youtube Data API to search for videos, but I am encountering an issue with restricted content appearing in the results. Specifically, music videos from Vevo are showing up even though I only want videos that can be embedded or placed ...

What is the best way to tally up all the image tags contained in an HTML string?

After generating some HTML using a WYSIWYG editor, I need to work with it in my Angular project. Imagine I have the following stringified HTML: '<p>Here is some text with an image</p><br><img src="data:base64;{ a base64 stri ...

How to shift an image to the right side of the navbar

Is it possible to change the position of an image within a navbar from left to right? I have tried using the float property but it doesn't seem to work. .logo-img{ float: right; margin: 0px 15px 15px 0px; } <a class="navbar-brand logo-img" ...

What is the best way to use regular expressions in JavaScript to pull out a date value from a string?

I am working with a string in this format: var value = "/Date(1454187600000+0300)/". From this, I need to extract a date format like 1/30/2016. Currently, I have the following code snippet: var value = "/Date(1454187600000+0300)/"; // I need to extract f ...

What is the process for transferring a Pulumi Output<T> to the container definition of a task in ECS?

When creating a generic ECS service that deals with dynamic data, it is important to note that the containerDefinition within a Task Definition must be provided as a single valid JSON document. The code snippet for this setup looks like: genericClientServi ...