Pass JS POST request data as body parameters

Is there a way to send a parameter as the post body to an API while also including the required Authorization header with the API key?

  • How can I include a post body request with data set as "server_id: 12345"?
  • What is the method to display the JSON response from the API on my webpage?
document.getElementById("1").addEventListener("click", PowerOff);
function PowerOff() {
  "";

  console.log("Doing");

  fetch(url, {
    method: "POST",
    headers: {
      Authorization: "CrocodileZebraGiraffe",
      "Content-Type": "application/json",
    }
  });
}

Answer №1

Ensure your body data type aligns with the "Content-Type" header to receive the expected json response. Follow the standard then method for processing the data.

var data = {server_id: 12345} //can be created within the function if it remains constant
function PowerOff() {
  "";

  console.log("Executing");

  fetch(url, {
    method: "POST",
    headers: {
      Authorization: "CrocodileZebraGiraffe",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data)
  }).then(response=>{
    console.log('Success: ', response);
    //if you need to store this response for later use, assign it to a variable
  }).catch(err => {
    console.log('Error: ', err)
  });
}

Answer №2

To enhance your API request, consider adding a new custom property named body and assigning it any desired data in the form of a stringified object:

const payload = {user_id: "67890"};
fetch(serverUrl, {
  method: "POST",
  headers: {
    Authorization: "LionElephantTiger",
    "Content-Type": "application/json",
  },
  body: JSON.stringify(payload)
}).then((response)=> {
   // Process the response as needed
});

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

Issue with setting innerHTML of element in AngularJS app upon ng-click event

Look at this block of HTML: <div class="custom-select"> <div class="custom-select-placeholder"> <span id="placeholder-pages">Display all items</span> </div> <ul class="custom-select- ...

Converting PHP XML to JSON while retaining individual Tag Elements

Is there a way to convert an XML document to JSON without losing single tag elements? For example, in my XML: <myTag><singleTag internValue="bli bla blo"/></myTag> In my PHP code: $xml = simplexml_load_string($result); $json = j ...

"Utilizing jQuery to apply a class based on the attributes of CSS

Is there a way in jQuery (or plain JS) to create a condition based on whether a div has a specific CSS attribute? For instance, I need jQuery to apply position:fixed to an element's CSS when another element has display:none, but switch back to positi ...

Having trouble retrieving IDs in a Many-to-Many relationship with Django 2.0.2

I'm currently working on a web application using Django 2.0.2 with Full Calendar and Bitnami Stack integration. I've encountered some challenges with understanding the Many-to-Many relationship in Django. My goal is to match all relevant resource ...

What is the best way to transform a string response into properly formatted JSON data?

Hello, I'm currently working on converting a string response into a valid JSON list of objects in Python. value= "{ActionSuccess=True; AdditionalActionsBitMask=0},{ActionSuccess=True; AdditionalActionsBitMask=0}" I attempted to use json.loa ...

The local database is not receiving any values

Retrieving data from a JSON URL on the server and saving it to a local database is causing an error. The process involves fetching a JSON array, which appears in the Logcat messages, but encounters issues when attempting to store the values in the local da ...

What is the Best Way to Enable Tooltips to Function from External Elements?

I am currently designing a map that features points with tooltips. When hovered over, the tooltips function correctly. I am interested in exploring the possibility of making the tooltips interact with an external navigation bar. My goal is to have specifi ...

Tips for converting Form Input field data into JSON Format with Jquery Ajax

I need to convert data from the controller into JSON format, but it is currently in string form. Is there a way to achieve this? I tried using headers for passing data in an AJAX call, but it doesn't convert the form field into JSON format. Due to the ...

Accessing variables from outside the query block in Node.js with SQLite

I'm looking to retrieve all the rows from a table and store them in an array called "arr". I need to access this stored array outside of the query section. Is there a way for me to get all the rows outside of the db.each function so that I can continu ...

When making an XMLHTTPRequest, Chrome often responds with an "Aw, snap"

In the development of my server-based multiplayer game using three.js, I have set up the server to operate as follows: game->Server2.php->Server.txt game->Server.php->Server.txt->game The process flow is as follows: 1.) The game is gener ...

What is the process of implementing session storage in an AngularJS directive?

I am trying to save values in Angular session storage within an Angular directive, but I am facing an issue where I only receive NULL. Can anyone provide assistance? app.directive('myDirective', function (httpPostFactory) { return { restrict ...

A guide on implementing listings in React Native through the use of loops

I am trying to display the data retrieved from an API, but I am encountering an error. // Retrieving the data. componentWillMount() { tokenner() .then(responseJson => { const token = "Bearer " + responseJson.result.token; ...

What is the best way to showcase information from an external API in react js?

As I develop my new app, I am integrating API data from . This feature will enable users to search for their favorite cocktail drinks and display the drink name fetched from the API on the page. However, I am encountering an error that says "Uncaught TypeE ...

Tips for updating form values with changing form control names

Here is an example of a form I created: public profileSettingsGroup = new FormGroup({ firstName: new FormControl('Jonathon', Validators.required) }) I also have a method that attempts to set control values in the form: setControlValue(contro ...

Mobile devices do not support internal link scrolling in Material UI

Currently, I'm utilizing internal links like /lessons/lesson-slug#heading-slug for smooth scrolling within a page. While everything functions perfectly on desktop, it ceases to work on mobile view due to an overlaid drawer nav component. Take a look a ...

Change JSON data into a text format

Looking for help with a Java issue I'm having. Despite reading tutorials and asking questions, I'm still struggling to apply the knowledge to solve my problem. Here's the issue: I need to read multiple json files in one place and convert t ...

How to Use Conditional In-Line CSS for Internet Explorer and Other Browsers

After inspecting the source code for this website, I noticed a cool feature where the page changes based on your scrolling position. It creates a visually appealing effect. Upon further examination of the source in FireFox, I observed the use of -webkit-t ...

Adding Elements in Real-Time to a jQuery Mobile ListView

I'm looking to inject dynamically fetched data, formatted in JSON, into my listview. I'm struggling with how to make it work. The mobile site is fetching the object in this structure: [ {"id":1, "start":"2011-10-29T13:15:00.000+10:00", "end ...

I am unable to log in using bcryptjs, but I have successfully been able to register a

Hey there! So I'm diving into Nodejs and I've managed to create a simple login/register API. For password encryption, I'm using bcryptjs. Testing it out on postman, I can successfully register a new user. However, when attempting to login wi ...

Utilize ES6 to import components for rendering on the server-side

In my ES6 React component file, I have a simplified version that utilizes the browser-specific library called store. Everything works perfectly fine on the browser: /app/components/HelloWorld.js: import React, { Component } from 'react'; import ...