Post Request rejected with "Missing body content" error during Fetch - javascript

I am sending a Post request, with JavaScript Fetch method. The post attempts to create a Microsoft Teams chat message, via the Microsoft Graph Teams API. However, the server rejects the post request, with the message "missing body content". The payload shows the message body is being sent (Please see screenshot). It appears that the server is rejecting my Post request because it can not parse the body, which is in json format. Can anyone advise how I fix this Fetch issue? I've attached a code snippet for your review.
const data = {content: 'Hello Word'};
const options = {
method: 'POST',
headers: {
Authorization: 'Bearer '+response.accessToken,
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
};
fetch(endpoint, options)
.then((response)=>{
const data = response.json();
console.log("RESPONSE1:", data);
return data;
})
.then((data)=>{
console.log("RESPONSE2:", data);
callback(data, endpoint);
})
.catch((error) => console.log("PUSHMSGRAPH-Error:", error));

Try using the API and post it from the reference page with this API
POST /teams/{team-id}/channels/{channel-id}/messages
const teamId = '5834e4c1-2897-4cc3-b21900b56';
const threadid = '19:1df3a1d...#thread.tacv2';
const options = {
authProvider,
};
const client = Client.init(options);
const chatMessage = {
body: {
content: 'Hello World'
}
};
await client.api('/teams/' + teamId + '/channels/' + threadid + '/messages')
.post(chatMessage);

Related

Fetch: HTTP GET Showing data not working via web api consuming gRPC

I'm trying see in console some data from a http Get method but it doesn't work, showing me error 400 and Idk how I get is errors... I did with the post method and it works well
I'm also trying to do authentication with bearer tokens but idk if this is correct
This is the fetch get method:
function getUsers() {
fetch(uri_3_2, {
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem("key")}`,
}
//the localStorage.getItem("key") is a key I have when I first to other fetch call,
//so this getUsers() is calling after the first fetch I have
})
.then(response => response.json())
.then(data => _displayItems(data))
.catch(error => console.error('Unable to get Users.', error));
}
function _displayItems(data) {
console.log(data.Email); //undefined
console.log(data.Username); //undefined
console.log(data); //this works but don't show the data, I have so it gives me error...
}
I think this one is correct but I will show anyway
Controller method
[HttpGet("getAllUserInfo_2"), Authorize] //message is empty but it works
public async Task<ActionResult<ListUsersResponse>> GetAll_2(MessageRequest message)
{
var results = await _userClient.GetAllUsersAsync(message);
return Ok(results);
}
gRPC service
public override Task<ListUsersResponse> GetAllUsers(MessageRequest request, ServerCallContext context)
{
ListUsersResponse response = new ListUsersResponse();
var query = from emp in _context.Users_4
select new ListUserResponse()
{
Username = emp.Username,
Email = emp.Email
};
response.LstUsers.AddRange(query.ToArray());
return Task.FromResult(response);
}

Bad respond when trying to get authentication token for Reddit api 'Application Only OAuth'

So i been trying to get access to the reddit api.
I registered to reddit. verified my mail. opened an app and got my credentials.
Followed this official documentation and also came across to this tutorial
All my efforts have failed and don't get any respond.
I am using nodejs. but also tried in postman and failed.
Tried 2 options using fetch and using axios:
const axios = require('axios');
const fetch = require('node-fetch')
const { URLSearchParams } = require('url')
class RedditApi {
clientId2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
clientSecret2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
authenticationUrl = `https://www.reddit.com/api/v1/access_token`;
BASE_URL = 'https://www.reddit.com/';
tokenAuth = null;
tokenExpirationTime = null;
currencyObj = null;
constructor(currencyObj) {
this.currencyObj = currencyObj;
console.log("constructor service")
}
async getAuthToken() {
const bodyParams = new URLSearchParams({
grant_type: "https://oauth.reddit.com/grants/installed_client",
device_id: "DO_NOT_TRACK_THIS_DEVICE"
});
console.log(this.clientId2, 'this.clientId');
debugger;
const headersObj = {
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
};
let response = null;
try {
response = await axios.post(this.authenticationUrl,
bodyParams,
{
headers: headersObj
});
debugger;
} catch (error) {
debugger;
console.error(error);
console.log(error.stack);
return null;
}
}
async getAuthToken2() {
try {
// Creating Body for the POST request which are URL encoded
const params = new URLSearchParams()
params.append('grant_type', 'https://www.reddit.com/api/v1/access_token')
params.append('device_id', 'DO_NOT_TRACK_THIS_DEVICE')
// Trigger POST to get the access token
const tokenData = await fetch('https://oauth.reddit.com/grants/installed_client', {
method: 'POST',
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}` // Put password as empty
}
}).then(res => {
debugger;
return res.text()
})
debugger;
if (!tokenData.error) {
debugger;
res.send(trendingResult)
}
res.status(tokenData.error).send(tokenData.message)
} catch (error) {
debugger;
console.log(error)
}
}
}
module.exports = RedditApi;
when using axios i get this respond: "Request failed with status code 401"
When using fetch i get this respond: "'403 Forbidden\nRequest forbidden by administrative rules.\n\n'"
Anybody knows what is the problem and how can i fix it?
Many thanks!

Sending data with fetch. How to include variable in body [duplicate]

I know that with the new Fetch API (used here with ES2017's async/await) you can make a GET request like this:
async getData() {
try {
let response = await fetch('https://example.com/api');
let responseJson = await response.json();
console.log(responseJson);
} catch(error) {
console.error(error);
}
}
But how do you make a POST request?
Long story short, Fetch also allows you to pass an object for a more personalized request:
fetch("http://example.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
name: myName,
password: myPassword
})
})
.then( (response) => {
//do something awesome that makes the world a better place
});
Check out the fetch documentation for even more goodies and gotchas:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Please note that since you're doing an async try/catch pattern, you'll just omit the then() function in my example ;)
if you want to make a simple post request without sending data as JSON.
fetch("/url-to-post",
{
method: "POST",
// whatever data you want to post with a key-value pair
body: "name=manas&age=20",
headers:
{
"Content-Type": "application/x-www-form-urlencoded"
}
}).then((response) =>
{
// do something awesome that makes the world a better place
});
The best way to POST form data to a PHP-script is the Fetch API. Here is an example:
function postData() {
const form = document.getElementById('form')
let data = new FormData()
data.append('name', form.name.value)
fetch('../php/contact.php', {
method: 'POST',
body: data,
}).then(response => {
if (!response.ok) {
throw new Error('Network response was not ok.')
}
}).catch(console.error)
}
<form id="form" action="javascript:postData()">
<input id="name" name="name" placeholder="Name" type="text" required>
<input type="submit" value="Submit">
</form>
Here is a very basic example of a PHP-script that takes the data and sends an email:
<?php
header('Content-type: text/html; charset=utf-8');
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
$to = "test#example.com";
$subject = "New name submitted";
$body = "You received the following name: $name";
mail($to, $subject, $body);
2021 answer: just in case you land here looking for how to make GET and POST Fetch api requests using async/await or promises as compared to axios.
I'm using jsonplaceholder fake API to demonstrate:
Fetch api GET request using async/await:
const asyncGetCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncGetCall()
Fetch api POST request using async/await:
const asyncPostCall = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
});
const data = await response.json();
// enter you logic when the fetch is successful
console.log(data);
} catch(error) {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
}
}
asyncPostCall()
GET request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
POST request using Promises:
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
})
.then(res => res.json())
.then(data => {
// enter you logic when the fetch is successful
console.log(data)
})
.catch(error => {
// enter your logic for when there is an error (ex. error toast)
console.log(error)
})
GET request using Axios:
const axiosGetCall = async () => {
try {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts')
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosGetCall()
POST request using Axios:
const axiosPostCall = async () => {
try {
const { data } = await axios.post('https://jsonplaceholder.typicode.com/posts', {
// your expected POST request payload goes here
title: "My post title",
body: "My post content."
})
// enter you logic when the fetch is successful
console.log(`data: `, data)
} catch (error) {
// enter your logic for when there is an error (ex. error toast)
console.log(`error: `, error)
}
}
axiosPostCall()
Here is a solution for a POST request using node-fetch, with async/await.
async function post(data) {
try {
// Create request to api service
const req = await fetch('http://127.0.0.1/api', {
method: 'POST',
headers: { 'Content-Type':'application/json' },
// format the data
body: JSON.stringify({
id: data.id,
foo: data.foo,
bar: data.bar
}),
});
const res = await req.json();
// Log success message
console.log(res);
} catch(err) {
console.error(`ERROR: ${err}`);
}
}
// Call your function
post() // with your parameter of Course
Here is a complete example: After spending hours tinkering with incomplete code snippets I finally managed to post some json from javascript, pick it up using php on a server, added a data field and finally updated the original web page. Here is the HTML, the PHP and the JS. My thanks to everyone who posted the original code fragments collected here. Similar code is on-line here: https://www.nbest.co.uk/Fetch/index.php
<!DOCTYPE HTML>
<!-- Save this to index.php and view this page in your browser -->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Fetch Example</title>
</head>
<body>
<h1>Javascript Fetch Example</h1>
<p>Save this to index.php and view this page in your browser.</p>
<button type="button" onclick="myButtonClick()">Press Me</button>
<p id="before">This is the JSON before the fetch.</p>
<p id="after">This is the JSON after the fetch.</p>
<script src="fetch.js"></script>
</body>
</html>
<!-- --------------------------------------------------------- -->
// Save this as fetch.js --------------------------------------------------------------------------
function success(json) {
document.getElementById('after').innerHTML = "AFTER: " + JSON.stringify(json);
console.log("AFTER: " + JSON.stringify(json));
} // ----------------------------------------------------------------------------------------------
function failure(error) {
document.getElementById('after').innerHTML = "ERROR: " + error;
console.log("ERROR: " + error);
} // ----------------------------------------------------------------------------------------------
function myButtonClick() {
var url = 'json.php';
var before = {foo: 'Hello World!'};
document.getElementById('before').innerHTML = "BEFORE: " + JSON.stringify(before);
console.log("BEFORE: " + JSON.stringify(before));
fetch(url, {
method: 'POST',
body: JSON.stringify(before),
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => success(response))
.catch(error => failure(error));
} // ----------------------------------------------------------------------------------------------
<?php
// Save this to json.php ---------------------------------------
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
$decoded['bar'] = "Hello World AGAIN!"; // Add some data to be returned.
$reply = json_encode($decoded);
}
header("Content-Type: application/json; charset=UTF-8");
echo $reply;
// -------------------------------------------------------------
?>
In this article, I described about the Second Parameter of fetch().
For submit JSON data
const user = { name: 'Sabesan', surname: 'Sathananthan' };
const response = await fetch('/article/fetch/post/user', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(user)
});
For submit form
const form = document.querySelector('form');
const response = await fetch('/users', {
method: 'POST',
body: new FormData(form)
})
For file upload
const input = document.querySelector('input[type="file"]');
const data = new FormData();
data.append('file', input.files[0]);
data.append('user', 'foo');
fetch('/avatars', {
method: 'POST',
body: data
});

My POST request is failing with a 'Request with GET/HEAD method cannot have body' error

I am trying to use Zoho Creator's ADD RECORDS DATA API (https://www.zoho.com/creator/help/api/v2/add-records.html)
And here's the URL to help you understand my issue. The URL below will show you a JSON of all the variables involved before I run the POST method.
https://vp-expo-node-server.herokuapp.com/eticket/
This above link will show you the result of this controller
exports.addOneExhibitorToCreator = async function(req, res, next) {
try {
const token = await getAccessToken();
const url = process.env.ZOHO_CREATOR_FORM_URL + "/Add_Organisation";
// const organisation = req.body;
const organisation = {
data: {
isActive: true,
Organisation_Name: "Test With Alim",
Type: "Exhibitor",
Short_Name: "test",
Email: "test#fourplusmedia.com",
},
};
const options = {
Method: "POST",
Headers: {
"Content-Type": "application/json",
Authorization: "Zoho-oauthtoken " + token,
},
body: JSON.stringify(organisation),
};
const functionForResponse = "const response = await fetch(url, options);";
// const response = await fetch(url, options);
// const data = await response.json();
res.status(200).json({
status: "success",
token,
options,
url,
organisation,
functionForResponse,
});
} catch (err) {
console.log(err);
res.status(500).json({
err,
});
}
};
When I uncomment these 2 lines in the above controller
const response = await fetch(url, options);
const data = await response.json();
I get this result
https://vp-expo-node-server.herokuapp.com/eticket/response
As I don't know how to display the error on the browser I tried to console.log it and I got this error in the console
TypeError: Request with GET/HEAD method cannot have body
at new Request (/Applications/MAMP/htdocs/vp-expo-node-server/node_modules/node-fetch/lib/index.js:1199:10)
at /Applications/MAMP/htdocs/vp-expo-node-server/node_modules/node-fetch/lib/index.js:1409:19
at new Promise (<anonymous>)
at fetch (/Applications/MAMP/htdocs/vp-expo-node-server/node_modules/node-fetch/lib/index.js:1407:9)
at exports.addOneExhibitorToCreatorResponse (/Applications/MAMP/htdocs/vp-expo-node-server/controllers/eticketController.js:82:28)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
And I can confirm that the this line in the console.log
at exports.addOneExhibitorToCreatorResponse (/Applications/MAMP/htdocs/vp-expo-node-server/controllers/eticketController.js:82:28)
points to the uncommented lines...
So there's something wrong I am doing in those 2 lines.. but according to me it's the right way to send a POST request.. and I have no clue how a POST request can get a Request with GET/HEAD method cannot have body error.
Any help would be appreciated. I've double checked it and I've even asked Zoho for help (they mentioned as it's a client side thing they couldn't do much to help)
I've got my answer in the comments but just posting an answer just in case someone else is facing 'REQUEST WITH GET/HEAD METHOD' error when trying to send a POST request.
As #CherryDT pointed out in my case the POST method was not being used as I had misspelt 'method' as 'Method' (and I had committed the same mistake with 'headers' as 'Headers')..
So the 'method' property was not being used at all and it was defaulting to 'GET'... and hence the error.

issue with making a call using fetch and jwt

*My goal here is to get the location of bikes from a bike-sharing company's API.
I did Steps 1 and 2 using Postman. but ill try to integrate it into my code once I get the hang of it.
The first step is to verify your email and generate an Auth token. This requires only a verifiable email address. Make a POST request to https://web.spin.pm/api/v1/magic_links with the body:
{"email": "sampleemail#gmail.com"}
From there, you will need to find the token within your email. This token needs to be sent with a POST request to
https://web.spin.pm/api/v1/auth_tokens with the body:
{
"grant_type": "magic_link",
"magic_link": {
"email": "<email>",
"token": "<token>"
}
}
This request returns a JSON that looks like this: {"jwt":"eyJ0eXAiOiJ.....cXVLw","refreshToken":"2cb07....bab5030","existingAccount":false}
To get the position of vehicles so a GET-Request to https://web.spin.pm/api/v3/vehicles?lng=-77.0146489&lat=38.8969363&distance=&mode= User Header Authorization: Bearer to Authenticate and use the jwt-Token we got from the Auth request.
You will get something like this as return JSON {"vehicles":[{"lat":37.69247,"lng":-122.46595,"last4":"3595","vehicle_type":"bicycle","batt_percentage":null,"rebalance":null}, … ]}
Step 3 is done using (async/awit function) using fetch where I am having the problem with. I copy-pasted the jwt in my .env file and set up the proper headers.
I get a 401 response when making the call. when I tested step 3 using postman everything seems to work fine.
I have attached a screenshot of the error in this post. Hopefully its more clear, Thanks in advance.
const fetch = require("node-fetch");
require('dotenv').config();
async function getBikes()
{
const lat = '38.897574612438575';
const lng = '-77.01855164084469';
const api_url = `https://web.spin.pm/api/v3/vehicles?lng=${lng}&lat=${lat}&distance=&mode=`;
const jwt_key = process.env.BERER_KEY;
try{
const config = { method: 'GET',
headers: {json: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer'+ jwt_key
} },
rejectUnauthorized: false
};
const response = await fetch(api_url,config );
const data = await response.json(); //response.json() //headers //.jwt; //response.json()
if (response.ok)
{
console.log("STATUS CODE IS: "+response.status);
console.log('My JWT:', response);
return data;
}
else{
console.log("something went wrong ");
console.log("STATUS CODE IS: "+ response.status);
console.log( response);
}
} catch (error) {
console.log(error);
}
}
const y = getBikes();
console.log(y)
BEARER_KEY=eyJhbGciOiJIUzI1NiJ9.eyJ1c2V

Categories