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

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.

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.

Response body is null(Fetch request) [duplicate]

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?

How can I log in to an API and catch login errors using fetch on React Native?

I'm making an application that requires login to an API. I have a login form which sends the ID number and password to the API, and the API should respond like this:
[
{
"user_id":"032984",
"user_number":"140521351",
"token":"990nZtMtEUUMY"
}
]
If there is a login error, the API responds with:
[
{
"ERROR": "INVALID PASSWORD | NOT FOUND 1SELECT user_id, lastname, password, user_number FROM user where user_number = 'INVALIDVALUE'",
},
]
I want to be able to catch a login error with an if statement, like if there is the ERROR object in this JSON, display an alert, else login and save the user_id and token to variables I can use in different screens of the app to send more requests to the API, get those responses in JSON, and show the data I need.
How can I make this happen?
So far, here's the code for my login function:
// login function
_userLogin = () => {
this.setState({ isLoggingIn: true, message: '' });
// send request to API properly
fetch("https://api.company.com/v4/users/json.php", {
method: "POST",
// our headers
headers: {
'Content-Type': 'application/json',
'Connection': 'close',
'Accept': '*/*',
'User-Agent': 'InternalApp/0.1 (InternalApp; ReactNative) Expo/33',
'Accept-Language': 'en-US;q=1.0',
'Accept-Encoding': 'gzip, deflate'
},
// body of the request with number/password
body: JSON.stringify({
user_number: this.state.number,
password: this.state.password,
}),
})
.then(response => {
return response.json(); // make it json?!
}).then(responseData => {
// debug messages
console.log(responseData);
console.log("Moving on to parsing JSON"); // CODE WORKS TO HERE
// parse json
var jsonObj = JSON.parse(responseData); // CODE STUCK HERE
// debug messages
console.log("JSON parsed");
if (jsonObj.ERROR)
console.log("Error caught");
else
this.setState(prevState => ({
credentialJson: prevState.credentialJson = responseData,
isLoggingIn: false,
}))
this.props.onLoginPress();
})
};
I'm really new to React Native and StackOverflow, please excuse any formatting issues with the question. I hope I've provided enough detail.
Based on your comments to this answer and the output of console.log(responseData) your responseData is an Array and your data is an Object inside the first array element. Access your data through responseData[0]. For example:
responseData[0].token
//Should return "990nZtMtEUUMY"
Here is how you would check if there is an error set:
if(responseData[0].ERROR){}
Your fetch library fetch returns a Promise so if the API actually throws an error you can add a catch statement.
fetch(url).then().catch((error) => {
console.log("Error", error);
});
The other thing is the reason your code is halting at JSON.parse is that you already parsed the json in a previous .then clause (response.json()) so your trying to parse an object, not a string, which JSON.parse expects.

How should I send JWT token in axios GET request? [duplicate]

This question already has answers here:
How to send authorization header with axios
(12 answers)
Closed 4 years ago.
I'm new to Vue.js and want to make a request in a component to a restricted api:
computed: {
token () {
return this.$store.getters.getToken;
},
...
created () {
axios
.get( this.BASE_URL + '/profile/me')
.then( res => {
this.profile = res.data;
console.log('profile is:', res.data);
})
.catch(error => console.log(error))
},
The problem is that I don't know how to include the token into the request header. So not surprisingly I get 401 error in response.
And when I try
axios.defaults.headers.common['Authorization'] = this.token;
before the get request I receive OPTIONS /profile/me instead of GET /profile/me in the server logs.
How can I fix it?
Axios get() request accept two parameter. So, beside the url, you can also put JWT in it.
axios.get(yourURL, yourConfig)
.then(...)
In your case yourConfig might be something like this
yourConfig = {
headers: {
Authorization: "Bearer " + yourJWTToken
}
}
Also you can read about what you can put in your config here https://github.com/axios/axios.
Just search for "Request Config"
This works for me, try like -
let JWTToken = 'xxyyzz';
axios
.get(this.BASE_URL + '/profile/me', { headers: {"Authorization" : `Bearer ${JWTToken}`} })
.then(res => {
this.profile = res.data;
console.log('profile is:', res.data);
})
.catch(error => console.log(error))

Unable to send get request with headers using axios

Able to get the response in postman. But unable to get in axios. Getting html as response. What would be the problem?
import axios from 'react-native-axios';
var config = {
headers: {
'Content-Type': 'Application/Json',
'JsonStub-User-Key': '__USER__KEY',
'JsonStub-Project-Key': '__PROJECT__KEY'
}
};
export async function menuListByCategories() {
// simulate an asynchronous operation
const url = "http://jsonstub.com/burgers";
axios.get(url, {config})
.then((response) = > {
console.log(response.data);
})
.
catch ((error) = > {
console.log("axios error:", error);
});
}
Update: check the response of this code
You can add data: {} in config in order not to have Content-Type removed by axios. Check the answer of the question below.
Jsonstub response not showing

Categories

Resources