Response body is null(Fetch request) [duplicate] - javascript

This question already has answers here:
Trying to use fetch and pass in mode: no-cors
(9 answers)
Closed 3 years ago.
I am trying to make a request to the bank API, and get its branches in json format.
But I get an empty response.
Response
Although, if I insert the link into the browser, I will get the json format.
https://api.privatbank.ua/p24api/pboffice?json&city=Ивано-Франковск
This is how the request works Results
Errors Error
var address = document.getElementById('address').value;
function postData(url = '', data = {}) {
console.log(url);
return fetch(url, {
method: 'GET',
mode: 'no-cors',
headers: {
"Accept": "application/json",
'Access-Control-Allow-Origin':'*'
}
}).then(response => {
console.log(response);
if (response.ok)
{
response.json()
}
else {
throw new Error('Something went wrong');
}
});
}
postData(`https://api.privatbank.ua/p24api/pboffice?json&city=${address}`, {})
.then(data => console.log(JSON.stringify(data)))
.catch(error => console.error(error));
`

You're executing this as a no-cors request. These are severely restricted and you cannot read the body for it.
See stackoverflow.com/questions/45696999/fetch-unexpected-end-of-input
Also, you're not returning the result of .json(), so your function will in all cases return a promise to undefined.

I think you are trying to fetch data using no-cors when the site doesn't provide right headers then your code will not be able to access the response
a proper explanation can be seen in how to process fetch response from an 'opaque' type?

Related

How can I update the message body using gmail API in javascript

I have got the message body. Now I want to update it according to my needs. I am using this login/code. but it says 400 error. I think issue is in body parameter of the request. Would you please help me there?
var token = localStorage.getItem("accessToken");
var messageId = "18514426e2b99017";
async function updateMessageBody() {
var updatedBody = "Hello,\n\nThis is the UPDATED message body.\n\nBest regards,\nJohn";
const API_KEY = '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-CXIk';
const headers = {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
};
const response = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/18514426e2b99017/modify?key=['API_KEY']`, {
method: 'POST',
headers: headers,
body: JSON.stringify({
raw: window.btoa(unescape(encodeURIComponent(updatedBody)))
})
});
if (!response.ok) {
// throw new Error(`Request failed with status code ${response.status}`);
}
return await response.json();
}
updateMessageBody()
.then(response => {
console.log('Message body updated successfully:', response);
})
.catch(error => {
});
Checking the documentation, it states that a message body can't be altered once it has been created, meaning that once you have already created an email this message can't be changed. You can verify this here.
You can instead update a message draft which is possibly what you are trying to do, however using the endpoint you have in your code this won't be possible and will lead to the error message you are getting, try using instead the users.draft.update method that allows you to modify the content of the draft sitting in your mailbox. Please note as well that using the method users.messages does not have any update method as they only have the modify one's, those methods can only update the labels though so please be aware of that.

How to get content-type from the response headers with Fetch

I'm trying to access the returned content-type from my GET request so I can decide the kind of preview I want to like for html maybe pass through an iframe and for a PDF maybe some viewer. The problem is when I do console.log(response.headers) the object returned doesn't have content-type in it but when I check the networks tab the response headers has content-type:html/text. How can I get the content-type from the response headers?
this is how my GET request looks like
const getFile = async () => {
var requestOptions = {
method: "GET",
headers: context.client_header,
redirect: "follow",
};
let statusID = context.currentStatus.ApplicationID;
var response = await fetch(
process.env.REACT_APP_API_ENDPOINT +
"/services/getStatus?ApplicationID=" +
statusID,
requestOptions
);
console.log(response.headers);
if (response.ok) {
let fileHtml = await response.text();
setfileURL(fileHtml);
} else {
alert.show("Someting went wrong");
}
};
The Headers object isn't a great candidate for console.log() since it is not easily serialisable.
If you want to see everything in it, try breaking it down to its entries via spread syntax
console.log(...response.headers)
You'll probably find that you can in fact access what you want via
response.headers.get("content-type")
See Headers.get()

POST and GET API Request using fetch, cannot get the data

i'm trying to use this website: https://rel.ink/,
to implement a link-shortener in my webapp,
i can successfully POST a request, but what i GET back is the same object, not a shortened version.
I know it's basic stuff but i can't wrap my head around it.
The website states that i need to send more information with my GET request, but the GET requests should not contain a body yes?
Here's my code:
async function fetchNewLink() {
let newLinkJson = await postLink(input.value)
let newLink = await getShortLink(newLinkJson)
console.log(newLink)
}
function postLink(input) {
return fetch('https://rel.ink/api/links/', {
method: 'POST',
body: JSON.stringify({
url: input
}),
headers: {
"Content-type": "application/json"
}
})
.then(response => response.json())
.then(json => json)
}
function getShortLink(response) {
return fetch('https://rel.ink/api/links/' + response.hashid)
.then(result => result.json())
.then(newLink => newLink)
}
Many thanks
If what you're trying to get is the shortened version of the link, the API does not return exactly that when you make a request. However, all you need is the hashid it returns. The shortened link is the main website's url(https://rel.ink) concatenated with the hashid.
So if the API returns nJzb3n as the hashid when you make a POST request, the shortened link would be https://rel.ink/nJzb3n
I hope that helps.

can't get response status code with JavaScript fetch [duplicate]

This question already has answers here:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
(13 answers)
Closed 3 years ago.
I'm trying to create a login form. when I'm testing the service with Postman, I will get a body object with status code and etc.
But, with JavaScript fetch, I can't get body object and I just received an error:
export const login = (username,password) => {
return dispatch=>{
const basicAuth = 'Basic ' + btoa(username + ':' + password);
let myHeaders = new Headers();
myHeaders.append('Authorization', basicAuth);
myHeaders.append('Content-Type', 'application/json');
fetch(`${baseUrl}api/user/login`, {
withCredentials: true,
headers: myHeaders
})
.then(function (response) {
return response.json();
})
.then(function (json) {
dispatch(setLoginInfo(json))
})
.catch(err =>{
console.log(err)
dispatch(loginFailed())
});
}
}
I need to get status code in fetch.
The status code is the status property on the response object. Also, unless you're using JSON with your error responses (which some people do, of course), you need to check the status code (or the ok flag) before calling json:
fetch(`${baseUrl}api/user/login`, {
credentials: "include", // ¹ See note below
headers: myHeaders
})
.then(function(response) {
console.log(response.status); // Will show you the status
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
return response.json();
})
.then(// ...
Not checking that the request succeeded is such a common mistake I wrote it up on my anemic old blog.
¹ You had withCredentials: true, but the documentation says it's credentials: "include". (Thank you aderchox for pointing that out.)
The status is present in the response object. You can get it inside your first then block
.then(function (response) {
console.log(response.status);
return response.json();
})
Since you are returning response.json(), the subsequent then and catch only gets the result of response.json() which is the body of the response.

Fetch POST Unexpected end of input Erorr

I'm trying to do a POST request for authentication in Redux and I'm passing email & password as the body but it returns this error in the console:
Uncaught (in promise) SyntaxError: Unexpected end of input
I looked around for the answer and many people suggested that it might be a missing } brace but I looked for it and I don't think it's that.
Here is my fetch function.
export function loginUser(creds) {
let config = {
mode: 'no-cors',
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: `email=${creds.email}&password=${creds.password}`
};
return dispatch => {
dispatch(requestLogin(creds));
return fetch('http://localhost:4000/api/authenticate', config)
.then(response =>
response.json()
.then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
dispatch(loginError(user.message));
return Promise.reject(user);
} else {
localStorage.setItem('id_token', user.token);
dispatch(receiveLogin(user));
}
});
};
}
The fetch POST method calls the API and I see it in the networking tab and I see the response too but the fetch request stops at .then(response => after the url and config.
It's been two days and still can't find the solution. By the way, this works fine in Postman(chrome extension), so nothing wrong with the API.
Thanks
Answer EDIT: The issue was related to CORS, so for anyone having the same issue as I did.
I solve the same question when I remove
mode: 'no-cors'
from the config.
Anyway you could simplify your snippet code to:
fetch('http://localhost:4000/api/authenticate', config)
.then(response => response.json())
.then(({ user, response }) => {
And you should might add catch method to handle an Error object.

Categories

Resources