fetch. Processing 500 responses from the server - javascript

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*/);

Related

'Missing draft message' in 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));

Response data returns undefined from asp.net web api to vue.js

currently I'm fetching data from my api to front-end. I checked and my request body is arriving to server side. But after doing things when it comes to returning the token it always returns undefined data to vue.js:
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody]User user)
{
var result = await _accountRepository.LoginAsync(user.username, user.password);
if (string.IsNullOrEmpty(result))
{
return Unauthorized(result);
}
Debug.WriteLine(result.ToString()); // this works and I can see the token
return Ok(result);
}
When it comes here:
methods: {
login() {
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
}).then(response => {
console.log(response.data); // this is always undefined
})
.catch(e => {
console.log(e);
});
},
}
Please help I can't see any errors here. I'm confused.
You need to call either Response.text() or Response.json() depending on what data you expect. These methods return a Promise that resolves to the data.
E.g. for JSON:
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e));

send request using Fetch method

I need to send request using 'fetch' method. I need to send below data to my header
I need to send below data in request body
i am trying to do it using below code. but actually I have not proper idea to do it. can u help me.
fetch("http://disaida.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
PREPAY: ppy,
InputParameters: int
})
})
.then( (response) => {
});
Your data format is incorrect.
TRY
Also, based on your description, you might have to add the cookie property to your header
let data = {
PREPAY: {
InputParameters: {
P_USER_NAME : "SANJEEWA.LAKNATH1#HUAWEI.COM"
}
}
}
fetch("http://disaida.com/api/endpoint/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then( (response) => {
console.log("RR"+response.json())
}).catch(err => console.log("error",err));

Fetch call freezes

I am using fetch to read data from a API:
async _getDcnDetail(dcnId) {
return await fetch(API_URL+'get_dcndetail', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer '+ this.state.accessToken
},
body: JSON.stringify({
DcnId: dcnId
})
}).then(response => response.json());
}
Then I call it:
async componentDidMount() {
let response = await this._getDcnDetail(dcn.DcnId);
console.log(response);
}
But it "waits" eternally, it is not resolving the promise.
As I understand fetch returns a promise which gets resolved by response.json(). I use "await" to wait the promise to be resolved, so not sure, what is wrong.
First of all check if some error occured on your POST request
async _getDcnDetail(dcnId) {
return await fetch(API_URL+'get_dcndetail', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer '+ this.state.accessToken
},
body: JSON.stringify({
DcnId: dcnId
})
}).then(response => response.json())
.catch(err => alert("maybe some error occured"));
}
Additionally, you should refactor this as,
async _getDcnDetail(dcnId) {
try{
const response = await fetch(API_URL+'get_dcndetail', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer '+ this.state.accessToken
},
body: JSON.stringify({
DcnId: dcnId
})
});
response = response.json();
return response;
} catch(e){
console.log("error", e);
throw err;
}
}
Do have a look on promises and async/await

fetch API POST request response

I am trying to get output from the post request once the form has been submitted but I get a promise response rather than the actual data when posting the form
fetch('localhost/clients', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(formData)
}).then(response => {
console.info('Sending Message ...')
console.info(response.json())
}).catch (error => {
console.log(error)
})
The data gets passed to the backend however I want to return the data thats been outputted by the API server.
response.json() returns a Promise. You need to use it like below.
fetch('localhost/clients', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(formData)
}).then(response => {
return response.json();
}).then(jsonResponse => {
console.log(jsonResponse);
}).catch (error => {
console.log(error)
})

Categories

Resources