How to get response with axios api with "GET" method in react native - react-native

Here is my code:
axios({
method: "GET",
url: "http://112.196.108.244:9002/api/survey/question/get-question/not-answered/?surveyId=",
headers: {
"content-type": "application/json",
Authorization: `Bearer token-key`,
},
body: {
id: "68367859",
isMandatory: "false",
paginationFilter: { limit: 10, offset: 0, order: "DESC" },
filterInput: {
locationIds: ["1", "4011403", "4012144"],
categoryIds: [
"twoSubCategories/7898496",
"domains/7895290",
"subCategories/7896491",
],
},
},
})
.then((response) => {
console.log("response", response);
})
.catch((error) => {
console.log("error", error.response.data);
});
this code gives me error:
The error in console is-
details: "uri=/api/survey/question/get-question/not-answered/"
message: "document key is not valid."
status: 400

You're passing the id in the body. There are two problems at play here:
GET requests shouldn't use a body as part of the request. Check this answer.
What you want to do is pass the id (Which I assume is the survey id) as a query parameter. Something like this should work:
axios({
method: 'GET',
url: 'http://112.196.108.244:9002/api/survey/question/get-question/not-answered/',
headers: {
'content-type': 'application/json',
Authorization: "Bearer token-key"
},
params: {
surveyId: "68367859"
}
})
Add other params as necessary.

Related

Error in API response saying required parameters React native

When I call API I am getting below error in response. please find below is code and error message.
TEST RESPONSE:
{
"responseData": {"limit": ["Limit is required"],
"module_type": ["Module type required"],
"section": ["section value \"liveability || investment || recommend\" is required"],
"skip": ["Skip is required"]
}
Implemented code:
fetch( 'https://api.dotcomkart.com/api/homePagePropertyList?', {
method: 'POST',
body: JSON.stringify({
skip: 0,
limit: 10,
module_type:'buy',
section: 'liveability'
}),
})
Try this way
import FormData from 'FormData';
...
var data = new FormData();
data.append("skip", "0");
data.append("module_type", "buy");
....
fetch('YOUR_URL', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
})
.then((response) => response.json())
.then((responseJson) => {
console.log('response object:',responseJson)
})
.catch((error) => {
console.error(error);
});
Sometimes when you work with REST API call you have to work with correct headers.
In your case I suppose your are missing two important headers required to activate a good communication between client and servers:
accept
content-type
Please review your code based on this one:
fetch('https://api.dotcomkart.com/api/homePagePropertyList?', {
method: 'POST',
headers: {
"accept": "application/json",
"content-type": "application/json"
},
body: JSON.stringify({
skip: 0,
limit: 10,
module_type:'buy',
section: 'liveability'
}),
})
I think the server is returning "missing" parameters because is not able to understand the type of content. With Content-Type you should be able to instruct the server on how to parse your data.

How to add header in new Onesignal React-native

Error: {"errors": ["Please include a case-sensitive header of Authorization: Basic <YOUR-REST-API-KEY-HERE> with a valid REST API key."], "reference": ["https://documentation.onesignal.com/docs/accounts-and-keys#section-keys-ids"]}
I tried as below but error as given above
sendNotification = async (data) => {
const { userId } = await OneSignal.getDeviceState();
const notificationObj = {
contents: { en: "Message Body" },
include_player_ids: [userId],
Authorization: "Basic APIKEY",
headings: { en: 'You have new notification' },
android_channel_id: 'id',
template_id: 'id',
buttons: [{ "id": "open_flat", "text": "OPEN HOSTING", "icon": "ic_menu_share" }],
include_external_user_ids: ["13245-123455"],
};
const jsonString = JSON.stringify(notificationObj);
OneSignal.postNotification(jsonString, (success) => {
console.log("Success:", success);
}, (error) => {
console.log("Error:", error);
});
};
//Sending demo
useEffect(() => {
sendNotification()
})
I am getting the error :
Error: {"errors": ["Please include a case-sensitive header of Authorization: Basic with a valid REST API key."], "reference": ["https://documentation.onesignal.com/docs/accounts-and-keys#section-keys-ids"]}
Few months i tried to send notification with fetch with contenttype and Auth header
You need to replace APIKEY with your actual API key, e.g. your API key is "MY_API_KEY123456", then the header should be Authorization: "Basic MY_API_KEY123456"
FOR ANY ONE HAS THIS ERROR
let headers = {
'Content-Type': 'application/json; charset=utf-8',
Authorization: `Basic '<API-KEY-HERE>'`,
};
let endpoint = 'https://onesignal.com/api/v1/notifications';
let params = {
method: 'POST',
headers: headers,
body: JSON.stringify({
app_id: 'App Id',
include_external_user_ids: [{'userid'},{'userid2'}], --> Optional
headings: { en: 'DATA'},
contents: { en: 'DATA'},
buttons: [{ "id": 'id', "text": 'OPEN', "icon": "ic_baseline_open_in_new_24" }], --> OPTIONAL
data: 'Extra data as json'
}),
};
fetch(endpoint, params).then(res => { console.log('sucess NotiButton') }).catch(error => console.log('error' + error));

Vuejs: axios; Passing custom header in POST method

We are making an axios POST call from VueJs, need to pass a custom header. The way it is coded now, the custom header is not getting passed to the server script, other headers are getting passed. Please let me know what I might be doing wrong. Appreciate your help.
axios({
method: 'post',
url: urltocall,
data: strjson,
config: {
headers: {
'Access-Control-Allow-Origin': 'http://localhost:1337',
'Accept': 'application/json',
'Content-Type': 'application/json',
'username': 'test1'
}
}
})
.then(function (response) {
}
The headers object should not be put into a "config" object.
It's just...
axios({
method: 'post',
url: urltocall,
{
headers: {
....
Try doing it like this:
axios
.post(urltocall, myDataAsJSON, {
headers: {
"Access-Control-Allow-Origin": "http://localhost:1337",
"Accept": "application/json",
"Content-Type": "application/json",
"username": "test1"
}
})
.then(response => {
console.log("Success: " + response.data);
})
.catch(error => {
console.log("Error: " + error.response.data);
});
By the way, based on your 'Content-Type': 'application/json',, I know you're trying to send a JSON object, but where/what is this object?
Also, refer to the Full documentation for more information.

React Native can't get response from localhost

i'm studying with React Native,
but i can't get response properly
my fetch code is :
try {
let response = fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
console.log(response);
the response is :
the api response which i get from api when i try postman:
my php api is :
but my debugger console response is
fetch() function return a promise, so you should resolve this promise using one of this 2 methods:
1/ Using .then()
fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
).then(response => {
console.log(response); //<- your response here
}).catch(error => {
console.log(error); //<-catch error
});
2/ Using async/await syntax: you should add async keyword on the function where you call fetch
async getResponse(){
try {
let response = fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
console.log(response); //<- your response here
} catch(e){
console.log(e);<-catch error
}
}
You can send it using formdata:
let formData = new FormData();
formData.append('firstname', 'test');
If you do this, you don't have to use JSON.stringify:
fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: data
}
...
fetch is an asynchronous method, meaning it needs a .then callback. The data that immediatley comes from this then has a json() method attached to it to retrieve the actual data in a readable format.
fetch("http://192.168.1.106/little_api/index.php", {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(response => response.json())
.then(data => {
console.log(data) // this should return your data
})
.catch(err => console.log(err))
As Mahdi N said in his response, you can use the async/await syntax to retrieve the data without needing the nested callbacks.

HttpClient or Http POST with header request not hitting to the server

I'm trying to issue an http request to validate user and in response i need to get token issued by the server.
this ajax call working fine
$.ajax({
url: '/token',
'data': JSON.stringify({ Id: "test", Password: "test" }),
'type': 'POST',
'processData': false,
'contentType': 'application/json',
success: function (response) {
console.log("token =" + response);
},
});
But i need it in angular so i tried below two methods but none of them worked.
1st
let header = new Headers({ 'Content-Type': 'application/json', 'processData': false});
let options = new RequestOptions({ headers: header });
this.http.post('/token', JSON.stringify({ Id: "test", Password: "test" }), options)
.map(response => {
debugger;
console.log("token =" + response);
});
2nd
this.httpClient.post<any>("/token",
{ 'Id': "test", 'Password': "test" },
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response'
});
what is wrong with them.
I am using Dotnet Core 2.1 and angular 5
Please help me to solve this issue.
Your methods are observables.
In order to send the request and get the result, you need to subscribe to them.
This is an example of the 2nd method.
this.httpClient.post<any>("/token",
{ 'Id': "test", 'Password': "test" },
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}).subscribe(response => {
console.log("token =" + response);
});