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

Leveraging the source of an image from asset variables

Lately, I've been experiencing issues with displaying images on my page, specifically when trying to show a list of images. The problem arises when attempting to store the image URL in a variable or object instead of hardcoding it directly into the s ...

After sending a GET request in AngularJS, simply scroll down to the bottom of the

Usually, I use something like this: $scope.scrollDown = function(){ $location.hash('bottom'); $anchorScroll(); } While this method works fine in most cases, I've encountered an issue when fetching data for an ng-repeat and trying t ...

Dealing with a Nodejs/Express and Angular project - Handling the 404 error

Recently, I decided to dive into learning the MEAN stack and thought it would be a great idea to test my skills by building an application. My goal was simple: display a static variable ('hello') using Angular in the HTML. However, I ran into an ...

Refresh a particular element using javascript

I'm new to Javascript and I am trying to refresh a specific element (a div) using only Javascript when that div is clicked. I came across the location.reload() function, but it reloads the entire page which doesn't fit my requirements. Upon clic ...

Exploring the automated retrieval of data from arrays in Java objects: A comprehensive guide

My goal is to automatically create Java objects from JSON data obtained from a REST API. The JSON array contains properties of different shops, and I aim to generate one object per shop with all its respective properties. The following code helped me achi ...

Saving the Auth0 user object in React Context for Typescript in a Next.js environment

I am working on integrating Auth0 user authentication into my React application using the useUser hook and the context API. My goal is to access the user object globally throughout the app by storing it in the userContext.tsx file: import { createContext, ...

When a HTML table is generated from imported XML, DataTables will be applied

I am facing a challenge with my code and would appreciate some help. I am trying to load an XML file using jQuery and then use DataTables on my HTML table. However, the plugin doesn't seem to be functioning correctly. When I manually create an HTML ta ...

What is the method for generating HTML output in various languages with gulp-data?

Here is the content of my gulp file: var gulp = require('gulp'); var posthtml = require('gulp-posthtml'); var mjml = require('gulp-mjml'); var nunjucksRender = require('gulp-nunjucks-render'); var data = require(&ap ...

What is the best way to save information from an ng-repeat loop into a variable before sending it to an API?

My goal is to store the selected value from ng-repeat in UI (user selection from dropdown) and assign it to a variable. function saveSelection() { console.log('inside function') var postToDatabase = []; vm.newApplicant.values ...

"Embrace the power of Ajax and JSON with no regrets

function register() { hideshow('loading', 1); //error(0); $.ajax({ type: 'POST', dataType: 'json', url: 'submit.php', data: $('#regForm').serialize(), su ...

Create a link for editing in a data table that can filter based on multiple column values and also enable global search on specific custom

How can I generate an edit link with a function that requires multiple parameters extracted from different data columns received via ajax? I have come across the render callback, but it seems to only return one column value at a time and my requirement is ...

Crashes within an HTML5 Canvas

Having recently started to explore Javascript and working with canvas elements, I've encountered a roadblock when trying to implement collision detection for the canvas walls. Typically, I have a small square drawn on the canvas that I can move aroun ...

Reacting to the surprise of TS/JS async function behaving differently than anticipated

It appears that I'm facing a challenge with the small method; not sure if my brain is refusing to cooperate or what's going on. async fetchContacts() { await this.http.get('http://localhost:3000/contacts') .subscribe(res =& ...

Reconstruct complete picture from IIIF JSON data

If the IIIF info.json is structured in the given manner: { "@context" : "http://iiif.io/api/image/2/context.json", "@id" : "http://iiif.nli.org.il/IIIF/FL47675519", "protocol" : "http://iiif.io/a ...

Adjusting the height of a vertical slider in Vuetify2 is not customizable

I've been trying to adjust the height of a vertical slider in vuetify2, but setting it to "800px" or using style="height:800px" doesn't seem to work as intended. Even though the box within my grid expands, the height of the slider remains unchan ...

How to make views in React Native adjust their size dynamically in a scrollview with paging functionality

Has anyone successfully implemented a ScrollView in React Native with paging enabled to swipe through a series of images? I am having trouble making the image views fill each page of the scroll view without hardcoding width and height values for the image ...

Having trouble with AES decryption on my nodeJS/ExpressJS server backend

Looking to decipher data post retrieval from mongoDb. The retrieved data comprises encrypted and unencrypted sections. app.get("/receive", async (req, res) => { try { const data = await UploadData.find(); const decryptedData = data. ...

Having trouble configuring React-Router-Dom correctly

Hey there, I'm currently working on a project using react-router-dom. It seems like I may have missed a step in following the instructions because I'm encountering the following issues: bundle.js:1085 Warning: Failed prop type: The prop `history ...

JavaScript implementation of Ancient Egyptian Multiplication using PHP code

Let's dive into the algorithm. If we have two integers, A and B (remember, only integers), that need to be multiplied, here is how it works: we continuously multiply A by 2 and divide B by 2 until B cannot be divided any further, or in other words, un ...

Get javax.json by utilizing Maven

I'm working on integrating the javax.json library into my project, so I included it in my pom.xml file as follows: <dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> <versio ...