'Missing draft message' in Javascript - javascript

I am working on this issue from last 3 days. I dived through the stack overflow, but of no use. There are the questions about "Missing draft message", but I am still getting this message. I have tried all the ways they have said. but I am still here.
Here is my code
const str = "My Draft";
const msgBody = btoa(str);
var token = localStorage.getItem("accessToken");
fetch(
"https://gmail.googleapis.com/gmail/v1/users/me/drafts?key=[my api key] HTTP/1.1",
{
method:"post",
ContentType: 'application/json',
Accept: 'application/json',
headers: {
"Authorization": `Bearer ${token}`,
},
message: {
raw: msgBody
}
}
)
.then((data) => data.json())
.then((response) => console.log(response));

please add message in body https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#supplying_request_options
const str = "My Draft";
const msgBody = btoa(str);
var token = localStorage.getItem("accessToken");
fetch(
"https://gmail.googleapis.com/gmail/v1/users/me/drafts?key=[my api key] HTTP/1.1",
{
method: 'POST',
ContentType: 'application/json',
Accept: 'application/json',
headers: {
"Authorization": `Bearer ${token}`,
},
body: JSON.stringify({ // Here changed
message: {
raw: msgBody
}
}),
}
)
.then((data) => data.json())
.then((response) => console.log(response));

Related

Why does my request return an ERR_BAD_REQUEST?

I am making a request from postman that returns the requested information without problem, additionally I did the test using curl and in the same way it returns the information successfully.But when doing it from axios it returns an ERR_BAD_REQUEST, the code is the following:
const axios = require('axios');
let payload = {
"payment_method": {
"type": "CARD",
"installments": 2,
"token": "tok_prod_some_token"
}
};
let config = {
method: 'post',
url: 'https://hereismyurl/v1/tokens/cards',
data:payload,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
'Authorization': 'Bearer pub_prod_some_public_key'
},
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
I can't understand what I'm sending wrong in my request

TypeError: Failed to execute 'fetch' on 'Window': Invalid name WITH Yelp API

Having trouble fetching the Yelp API in my react native app. Here is my code:
const getRestaurantsFromYelp = async (req, res) => {
const yelpUrl = `https://api.yelp.com/v3/businesses/search?term=restaurants&location=NYC`;
const apiOptions = {
method: 'GET',
headers: {
accept: 'application/json',
'x- requested - wth': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*',
Authorization: `Bearer ${YELP_API_KEY}`,
},
};
return await fetch(yelpUrl, apiOptions)
.then((res) => res.json())
.then((json) => setRestaurantData(json.businesses));
};
useEffect(() => {
getRestaurantsFromYelp();
}, []);
Your options object is not correct. Please remove
x- requested - wth as the wrong key or fix it.
Also, use the same type of key in your code the options have different type of keys with quotes and without.
So, I think this code should work.
const yelpUrl = `https://api.yelp.com/v3/businesses/search?term=restaurants&location=NYC`;
const apiOptions = {
method: 'GET',
headers: {
'accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Authorization': `Bearer ${YELP_API_KEY}`,
},
};
const response = await fetch(yelpUrl, apiOptions)
const { businesses } = response.json();
setRestaurantData(businesses);

How to make a fetch request to TinyURL?

I am trying to make a fetch request specifically a post request to tinyURL to shortern a url generated on my site. here is the tinyURL API
Currently, I am writing my code like this but it doesn't appear to be returning the short url.
the word tinyurl seems to be banned within links so all links
containing the word tinyurl have been replaced with "SHORT"
here is the tinyURL API https://SHORT.com/app/dev
import * as React from 'react'
interface tinyURlProps { url: string } export const useTinyURL = ({ url }: tinyURlProps) => { React.useEffect(() => {
const apiURL = 'https://api.SHORT.com/create'
const data = JSON.stringify({ url: url, domain: 'tiny.one' })
const options = {
method: 'POST',
body: data,
headers: {
Authorization:
'Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
Accept: 'application/json',
'Content-Type': 'application/json',
},
} as RequestInit
fetch(apiURL, options)
.then((response) => console.log(response))
.then((error) => console.error(error))
console.log('TinyUrl ran') }, [url])
}
The snippet below seems to work
const qs = selector => document.querySelector(selector);
let body = {
url: `https://stackoverflow.com/questions/66991259/how-to-make-a-fetch-request-to-tinyurl`,
domain: `tiny.one`
}
fetch(`https://api.tinyurl.com/create`, {
method: `POST`,
headers: {
accept: `application/json`,
authorization: `Bearer 2nLQGpsuegHP8l8J0Uq1TsVkCzP3un3T23uQ5YovVf5lvvGOucGmFOYRVj6L`,
'content-type': `application/json`,
},
body: JSON.stringify(body)
})
.then(response => {
if (response.status != 200) throw `There was a problem with the fetch operation. Status Code: ${response.status}`;
return response.json()
})
.then(data => {
qs(`#output>pre`).innerText = JSON.stringify(data, null, 3);
qs(`#link`).href = data.data.tiny_url;
qs(`#link`).innerText = data.data.tiny_url;
})
.catch(error => console.error(error));
body {
font-family: calibri;
}
<p><a id="link" /></p>
<span id="output"><pre/></span>

fetch. Processing 500 responses from the server

I send this request to the server:
fetch('/changeCountProductInCart', {
method: 'POST',
body: JSON.stringify({
product_id: this.dataset.product_id,
action: 'changeByInput',
nodeName: this.nodeName,
product_count: this.value
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}).then(res => {
if(res.ok) {
totalAmount();
} else if(!res.ok) {
return res.json();
}
}).then(body => {
this.value = body.stock;
});
I want to go to then only if the response from the server only is not in the range of 200-300,but I just started to delve into promise and can't find the answer to my question
P.S. I will be grateful for any help or hint
You need to catch the server error responses:
fetch('/changeCountProductInCart', {
method: 'POST',
body: JSON.stringify({
product_id: this.dataset.product_id,
action: 'changeByInput',
nodeName: this.nodeName,
product_count: this.value
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.catch(err => /* error getting server response*/);

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data[Learn More]

Please a I cann't solve this problem, someone can help me?
handleSubmit = event => {
event.preventDefault();
const email = document.querySelector(".email").value;
const senha = document.querySelector(".password").value;
alert(JSON.stringify({email, senha}));
const res = {
method: 'POST',
mode:'no-cors',
body: JSON.stringify({email,senha}),
headers: new Headers({
'Content-type': 'application/json',
'Authorization': 'Token Here',
}),
};
fetch('http://rhvagas-api/login', res).then(res => res.json())
.then(result => {
console.log(result);
})
}
ERROR:
postman:
I think there is problem with your body object.Because you are passing only value to body without key.
so body should be body: JSON.stringify({email:email, password:senha})

Categories

Resources