React Native - Request with URL that includes credentials - javascript

So I have to make requests to various urls with different domains which contains credentials
I've successfully managed to send one like this:
const resp = await fetch(`my-url-here`, {
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Authorization': `Basic ${base64.encode(my-key-here)}`
},
body: JSON.stringify(data)
})
However this works only for one domain while on the other I keep getting
[TypeError: Network request failed] on Android
[SyntaxError: JSON Parse error: Unexpected identifier "undefined"] on iOS (while executing the .json() method; I think the request is successful but with an empty response)
Every call on these domains work correctly using PostMan/ThunderClient
Any idea how to solve this?

Please share how you are processing response seems like request works fine but somehow there is an error while parsing the data into JSON.
invalid data contains in response which is not able to parse into JSON.

Related

I can not send parameter using GET with jQuery to node js REST API [duplicate]

I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).

POST request to Spotify API saying no token

I am getting this error message when I am trying a POST request:
{
"error": {
"status": 401,
"message": "No token provided"
}
}
The thing is I am passing in an access token by making a headers variable and assigning it to the headers for the post request like this:
const headers = {
Authorization: `Bearer ${accessToken}`
}
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
'headers': headers,
method: 'POST',
body: JSON.stringify({'name': name})
This fetch request is the one giving me the error I stated above. How can I fix this?
Headers object picture right before the fetch request
Here is the link to the GitHub: https://github.com/aoljaca/jamming
This code is in the src/utils/Spotify document
Thanks!
I tried running your code but it threw a different error before it it was able to reach that part of your program.
One possible debugging strategy is making sure the headers variable is still defined and includes the access key before returning the fetch request. Just print it to console before running that particular fetch. If it goes out of scope at some point in your promise chain then it could be null.
I'd also suggest using headers: headers instead of 'headers': headers.

why data is undefined in post method

I m using react js app and I try to post data to my api , but I got undefined insert for one time .
instead of 'url' I have working url.
this is my post method's code:
senddata(){
if(!this.formvalidation())
{
try{
let resulte = fetch('url',{
method:'post',
mode:'no-cors',
headers:{
'Accept':'application/json',
'Content-type': 'application/json'
},
body:JSON.stringify({
ID:this.state.code,
Blod:this.state.blod,
Allergic:this.state.allergicdescription,
Chronic:this.state.chronic_description
})
});
alert("post");
}catch(e){
alert("not post")
}
}
}
thanks.
You said mode:'no-cors' so any attempt to do anything which requires permission from CORS will fail silently.
Setting 'Content-type': 'application/json' requires permission from CORS.
Presumably, your server side code is not parsing the request body as JSON since the Content-Type header doesn't say it is JSON.
Since there is no parsed data, all the properties you want to read from the JSON will be undefined.
Don't use mode:'no-cors' if you want to POST JSON.

Simple GET method for DailyMotion API with Google AppScript is returning 503 error. How do I get it to work consistently?

Whenever I make the API request with GET method, it is returning a 503 error from Google AppScript. However, this same request is successfully getting response consistently when run from Postman or the web-browser.
The AppScript code returns a JSON response out of the blue at first call and all consecutive calls return with the error 503. This server response is showing up specifically to the AppScript code here.
The detailed error message is as follows:
Exception: Request failed for https://api.dailymotion.com returned code 503. Truncated server response: Gone. (use muteHttpExceptions option to examine full response) (line 24, file "DailyMotion")
function dailymotionArtist() {
var artistchannelID = 'x24dh63';
var requestOptions = {
'headers': {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cache-Control': 'no-cache'
},
'muteHttpExceptions': true,
method: 'GET'
}
var finalResponse2 = UrlFetchApp.fetch('https://api.dailymotion.com/user/' + artistchannelID + '?fields=followers_total%2Cviews_total', requestOptions);
Logger.log(finalResponse2.getContentText());
}
A 503 error message is generally representative of a server being unable to respond to a request temporarily, and is not normally a representation of an incorrect request - see description of the 503 code.
I would always suggest trying a request using Postman or another HTTP Client to test the API isn't just down temporarily before debugging a 503 code.

Sending Request body for GET method in AXIOS throws error

I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).

Categories

Resources