cannot convert auth token to string - javascript

I need to request POST method to authorize and set current location of user in my react-native application. As authorization header,I add token which I get before from API and saved it to the state. However, when I make request, I get error message of auth header empty. Whereas, when I console.log the token, it prints correctly. I guess the issue is something about the type of token. I tried to convert it to string, but nothing changed.
By the way, I checked request with static token - copy&pasted token instead of this.state.token and it worked perfectly, so it is clear that I live problem with converting the token.
Here is the code that I make request.
console.log("AUTH TOKEN: ", this.state.token);
var Url = "https://-----------";
return fetch(Url, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.state.token
},
body: JSON.stringify({'latitude': this.state.location.coords.latitude.toString(), 'longitude': this.state.location.coords.longitude.toString()})
})
// .then((response) => response.json())
.then((response) => {
console.log(response);
})
.done();
here is the result of request on console.
Has anyone lived such issue before?

Related

My GET request works fine in POSTMAN and Curl, but not in JavaScript code

When I make my get request with POSTMAN or Curl, it works just fine and I get the expected response. I just set type to GET, insert my URL and insert a key named token/email and set it to a token/email I get from another service.
But when I try to call the same service in code like this:
function getAll() {
const myHeaders = new Headers({
'Accept': 'application/json',
'token': 'MY TOKEN',
'email': 'MY EMAIL'
});
return fetch('https://apitul', {
headers: myHeaders,
method: 'GET'
})
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error('Something went wrong on api server!');
}
})
.then(response => {
console.debug(response);
}).catch(error => {
console.error(error);
});
}
I get 401 error. I also found out that the server is not receiving the token in the request header. Any ideas how I can fix this? Cheers.
To send your token in header use this: 'Authorization': 'Bearer yourToken'
Try to generate code using Postman, let's see if it helps. See attached.

How to access JSON body in the response object when status of 400/403/500 are sent?

Whenever server returns 200 status, I'm able to get the JSON msg property as response.
But when status code 400/403/500 is sent, the error is sent in the browser console and I can see my "msg" inside the error object(in the console)
How to extract it with response inside Angular to show it to the user?
Consider the following code :
res.status(403).json // {msg : "Password Incorrect"}
How should I access the msg field?
How would you catch both a 200 OR a 422 from a resource, both containing valid JSON in the body?
This is the only way I've figured it out so far.
fetch(`${endpoint}user/${record.id}/`, {
method: 'put',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${auth}`
},
body: JSON.stringify(record)
})
.then((result) => result.json())
.then((result) => {
if (result.id) {
dispatch(savedUser( result ));
} else {
dispatch(savingUserError( result ));
}
});

axios delete method gives 403

I am calling delete method from my node-js application.
Its working fine from Postman but giving me 403 while calling this API
from code.
Below is my sample code snippet:
const instance = axios.create();
instance.interceptors.request.use((config) => {
config.baseURL = 'https://test-dev.com/api/portfolio'
config.headers = { 'Authorization' : 'Bearer ' + <TOKEN>}
return config;
});
instance.delete('/admin?users=<VALUE>').then(function(response) {
console.log("Deleted: "+<VALUE>);
}).catch(function (error) {
console.log("Deletion failed with error:" + error);
});
EDIT:
Response (Coming from spring security APP):
Could not verify the provided CSRF token because your session was not found
I thought this is already handled by axios.
How can i pass this value in headers while calling delete method?
Any help?
You could either:
1 - Use the withCredentials property:
withCredentials: true
so:
axios.delete({
url: 'https://test-dev.com/api/portfolio/admin?users=' + <VALUE>,
headers: { 'Authorization' : 'Bearer ' + <TOKEN>},
withCredentials: true
}).then(function(response) {
console.log("Deleted: "+<VALUE>);
}).catch(function (error) {
console.log("Deletion failed with error:" + error);
});
The XMLHttpRequest.withCredentials property is a Boolean that
indicates whether or not cross-site Access-Control requests should be
made using credentials such as cookies, authorization headers or TLS
client certificates. Setting withCredentials has no effect on
same-site requests.
2 - Set CSRF headers
Either:
headers: {'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content')}
or
headers: {'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': 'your token here'}
or just:
headers: {'X-Requested-With': 'XMLHttpRequest'}
3 - Disable at own risk and if possible
Have a look at this article
So after a number of tries, I found it working.
Please follow the order sequence it's very important else it won't work
axios.delete(
URL,
{headers: {
Authorization: authorizationToken
},
data:{
source:source
}}
);

When using mode: no-cors for a request, browser isn’t adding request header I’ve set in my frontend code

in my React app, I have the following API POST to allow the user to edit their profile (name and image).
static updateProfile(formData, user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken()
}),
mode: 'no-cors',
method: "POST",
body: formData
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
The problem with the above is the header with the Authorization token is not being sent in the POST...
How can I get the Authorization header to be send in the fetch request above?
FYI, for non-multipart forms, the authorization token is sent successfully like so:
static loadProfile(user_id) {
const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
headers: new Headers({
'Authorization': getBearerToken(),
'Accept' : 'application/json',
'Content-Type' : 'application/json',
})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
You can’t use no-cors mode if you set any special request headers, because one of effect of using it for a request is that it tells browsers to not allow your frontend JavaScript code to set any request headers other than CORS-safelisted request-headers. See the spec requirements:
To append a name/value pair to a Headers object (headers), run these steps:
Otherwise, if guard is "request-no-cors" and name/value is not a CORS-safelisted request-header, return.
In that algorithm, return equates to “return without adding that header to the Headers object”.
Authorization isn’t a CORS-safelisted request-header, so your browser won’t allow you to set if you use no-cors mode for a request. Same for Content-Type: application/json.
If the reason you’re trying to use no-cors mode is to avoid some other problem that occurs if you don’t use, the solution is to fix the underlying cause of that other problem. Because no matter what problem you might be trying to solve, no-cors mode isn’t going to turn out to be a solution in the end. It’s just going to create different problems like what you’re hitting now.
By using below code you can make a fetch request with Authorization or bearer
var url = "https://yourUrl";
var bearer = 'Bearer '+ bearer_token;
fetch(url, {
method: 'GET',
withCredentials: true,
credentials: 'include',
headers: {
'Authorization': bearer,
'X-FP-API-KEY': 'iphone',
'Content-Type': 'application/json'}
}).then((responseJson) => {
var items = JSON.parse(responseJson._bodyInit);
})
.catch(error => this.setState({
isLoading: false,
message: 'Something bad happened ' + error
}));

Unexpected end of JSON input error in Post request on api using access token in react-native

I am posting the details of user in api ,using the access token in header which i got in sign up but getting this error --> Unexpected end of JSON input. My code is
postNameToApi()
{
console.log("inside post api");
fetch('https://MyPostApi', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization':'Bearer'+'Qwjubq41KAWw9uI2NMj4TPQ9t24PxC'
},
body: JSON.stringify({
dob:'1992-04-18',
gender: 'femanino',
is_professional:true,
is_referee:false
})
}).then((response) => response.json())
.then((responseData) => {
console.log("inside responsejson");
console.log('response:',responseData);
//this.setState({response:responseData});
}).done();
}
This is because your response is not in json format. Space is missing between Bearer and your token, i think this will solve your issue.
'Authorization':'Bearer '+'Qwjubq41KAWw9uI2NMj4TPQ9t24PxC'
Try your api call with postman first.

Categories