Ionic 2 get RESTful API issue - rest

I am getting a RESTful API, and I have some question about the getting JSON, here is the JSON I get:
{
"result": "success",
"user": {
"loggedIn": true,
"name": "Nulra",
"password": ""
}
}
And the part for getting the JSON in auth-service.ts:
login(credentials) {
if(this.data){
return Promise.resolve(this.data);
}
let opt: RequestOptions;
let myHeaders: Headers = new Headers;
myHeaders.set('Accept', 'application/json; charset=utf-8');
myHeaders.append('Content-type', 'application/json; charset=utf-8');
opt = new RequestOptions({
headers: myHeaders
})
return new Promise(resolve => {
this.http.get(apiUrl+'login/0/login?email='+credentials.email+'&password='+credentials.password, opt)
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
And in my login.ts:
doLogin() {
this.authService.login(this.loginData).then(data => {
console.log("NULRA CHECKING: ",data);
}, (err) => {
});
}
I discover it just getting the user part in JSON, and missing the result part in JSON when I inspect in the console log. How can I get the both result and user part?
the console log:
Object {loggedIn: true, name: "Nulra", password: ""}

Try this solution for get json object from REST-API please check
console.log("NULRA CHECKING: " + JSON.stringify(data)); output in console.
login.ts:
doLogin() {
this.authService.login(this.loginData).subscribe( (data) => {
console.log("NULRA CHECKING: " + JSON.stringify(data));
}, (error) => {
console.log("Error : " + error);
});
}
auth-service.ts:
login(credentials): Observable<any> {
let opt: RequestOptions;
let myHeaders: Headers = new Headers;
myHeaders.set('Accept', 'application/json; charset=utf-8');
myHeaders.append('Content-type', 'application/json; charset=utf-8');
opt = new RequestOptions({
headers: myHeaders
})
return this.http.get(apiUrl + 'login/0/login?email=' + credentials.email + '&password=' + credentials.password, opt)
.map((res: Response) => res.json());
}

Related

When requesting github to get access token i was getting "not found" error as response

here is the request:(i required node-fetch as fetch to do http requests on the server)
const { code } = req.body;
const data = new FormData();
data.append("client_id", process.env.GITHUB_CLIENT_ID);
data.append("client_secret", process.env.GITHUB_CLIENT_SECRET);
data.append("code", code);
data.append("redirect_uri", process.env.GITHUB_REDIRECT_URL);
fetch(`https://github.com/login/oauth/access_token`, {
method: "POST",
body: data,
headers: {
Accept: "application/json",
},
})
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err)
})
here is the response:
{ error: 'Not Found' }

capacitor community/http handle errors

I often use Axios to perform requests in my applications, however due to incompatibility with iphone, I had to use the capacitor-community/http library, however the try catch blocks are always returning success, even if there was an error in the request. How can I handle errors using this library?
try {
await Requester.auth.public.login(formData);
this.$store.dispatch('login', user);
this.$root.$emit('showToast', {
text: 'Seja bem vindo!',
color: 'success',
});
this.$router.push({ name: 'Cotacao' });
} catch (err) {
this.$root.$emit('showToast', {
text: err.response?.data ?? err.toString(),
color: 'error',
});
} finally {
this.loading.submitForm = false;
}
},
My request
const login = async (formData: AuthLoginFormData): Promise<User> => {
const res: HttpResponse = await Http.post({
url: `${BASE_URL}public/auth/login`,
headers: {
'Content-Type': 'application/json',
},
data: formData,
webFetchExtra: {
credentials: 'include',
},
});
return res.data;
};
Install Latest https://github.com/capacitor-community/http plugin
use function
public async login(formData: AuthLoginFormData){
let options = {
url: `${BASE_URL}public/auth/login`,
headers: {
'Content-Type': 'application/json',
},
data: formData,
webFetchExtra: {
credentials: 'include',
}
};
let response: HttpResponse = await Http.request(options);
if (response.status === 200) {
return Promise.resolve(res);
}
return Promise.reject(response.data);
}

Why does the result of http request return an empty array?

I've tried using axios and fetch to get data from an API endpoint, but turns out to have only returned an empty array. It works fine in Postman. What have I missed?
Using Axios
axios({
method: "get",
url: "/api/purchase/receivegoods/index?action=detail-grn",
params: {
goods_receive_id: 71,
},
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((response) => {
console.log(("response", response));
})
.catch((error) => {
console.log("error message: ", error.message);
});
Using Fetch
fetch(
"https://devactive.com/api/purchase/receivegoods/index?action=detail-grn",
{
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
params: {
goods_receive_id: 71,
},
}
)
.then((response) => response.json())
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});
EDIT:
The request is in JSON format. It looks like this (this is an example of an existing id:
{
"goods_receive_id" : 71
}
check for possible proxy configuration, postman uses system proxy by default.
You are not passing the data as the body when using Axios or Fetch. You are hitting the endpoint though. Try something like this:
data = {
"goods_receive_id" : 71
}
axios({
method: "get",
url: "/api/purchase/receivegoods/index?action=detail-grn",
data: JSON.stringify(data), // <- You add the data to the body here
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((response) => {
console.log(("response", response));
})
.catch((error) => {
console.log("error message: ", error.message);
});
or
data = {
"goods_receive_id" : 71
}
fetch(
"https://devactive.com/api/purchase/receivegoods/index?action=detail-grn",
{
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
data: JSON.stringify(data), // <- You add the data to the body here
}
)
.then((response) => response.json())
.then((result) => {
console.log("Success:", result);
})
.catch((error) => {
console.error("Error:", error);
});

responseData gives an error ReactNative

fetch(loginApi, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
Password: password,
UserName: username
})
})
.then(response => response.json())
.then(responseData => {
console.log(responseData); //// <--- getting error at this line
})
.catch(error => {
console.error(error);
});
enter image description here
Any idea how to solve it??? Thanks in advance.
maybe response data is not in json format try this
fetch(loginApi, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
Password: password,
UserName: username
})
}).then((e)=>{
console.log(e) //see what you get, if promise then use another then
})
Luckily I have found the solution.
var loginParams = {
Password: password,
UserName: username
};
var loginFormData = new FormData();
for (var param in loginParams) {
loginFormData.append(param, loginParams[param]);
}
fetch(loginApi, {
method: "POST",
headers: { /// <---- you can remove this headers if you are not using any headers in postman..
Accept: "application/json",
"Content-Type": "application/json"
},
body: loginFormData
})
.then(response => response.json())
.then(responseData => {
console.log(responseData); //// <--- getting error at this line
})
.catch(error => {
console.error(error);
});
for more information please check this enter link description here

Passing headers with axios POST request

I have written an Axios POST request as recommended from the npm package documentation like:
var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data)
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
And it works, but now I have modified my backend API to accept headers.
Content-Type: 'application/json'
Authorization: 'JWT fefege...'
Now, this request works fine on Postman, but when writing an axios call, I follow this link and can't quite get it to work.
I am constantly getting 400 BAD Request error.
Here is my modified request:
axios.post(Helper.getUserAPI(), {
headers: {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
},
data
})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
When using Axios, in order to pass custom headers, supply an object containing the headers as the last argument
Modify your Axios request like:
const headers = {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
}
axios.post(Helper.getUserAPI(), data, {
headers: headers
})
.then((response) => {
dispatch({
type: FOUND_USER,
data: response.data[0]
})
})
.catch((error) => {
dispatch({
type: ERROR_FINDING_USER
})
})
Here is a full example of an axios.post request with custom headers
var postData = {
email: "test#test.com",
password: "password"
};
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
};
axios.post('http://<host>:<port>/<path>', postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
To set headers in an Axios POST request, pass the third object to the axios.post() call.
const token = '..your token..'
axios.post(url, {
//...data
}, {
headers: {
'Authorization': `Basic ${token}`
}
})
To set headers in an Axios GET request, pass a second object to the axios.get() call.
const token = '..your token..'
axios.get(url, {
headers: {
'Authorization': `Basic ${token}`
}
})
const data = {
email: "me#me.com",
username: "me"
};
const options = {
headers: {
'Content-Type': 'application/json',
}
};
axios.post('http://path', data, options)
.then((res) => {
console.log("RESPONSE ==== : ", res);
})
.catch((err) => {
console.log("ERROR: ====", err);
})
All status codes above 400 will be caught in the Axios catch block.
Also, headers are optional for the post method in Axios
You can also use interceptors to pass the headers
It can save you a lot of code
axios.interceptors.request.use(config => {
if (config.method === 'POST' || config.method === 'PATCH' || config.method === 'PUT')
config.headers['Content-Type'] = 'application/json;charset=utf-8';
const accessToken = AuthService.getAccessToken();
if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken;
return config;
});
Shubham's answer didn't work for me.
When you are using the Axios library and to pass custom headers, you need to construct headers as an object with the key name 'headers'. The 'headers' key should contain an object, here it is Content-Type and Authorization.
The below example is working fine.
var headers = {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
}
axios.post(Helper.getUserAPI(), data, {"headers" : headers})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
We can pass headers as arguments,
onClickHandler = () => {
const data = new FormData();
for (var x = 0; x < this.state.selectedFile.length; x++) {
data.append("file", this.state.selectedFile[x]);
}
const options = {
headers: {
"Content-Type": "application/json",
},
};
axios
.post("http://localhost:8000/upload", data, options, {
onUploadProgress: (ProgressEvent) => {
this.setState({
loaded: (ProgressEvent.loaded / ProgressEvent.total) * 100,
});
},
})
.then((res) => {
// then print response status
console.log("upload success");
})
.catch((err) => {
// then print response status
console.log("upload fail with error: ", err);
});
};
axios.post can accept 3 arguments that the last argument can accept a config object that you can set header.
Sample code with your question:
var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data, {
headers: {Authorization: token && `Bearer ${ token }`}
})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
If you are using some property from vuejs prototype that can't be read on creation you can also define headers and write i.e.
storePropertyMaxSpeed(){
axios
.post(
"api/property",
{
property_name: "max_speed",
property_amount: this.newPropertyMaxSpeed,
},
{
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + this.$gate.token(),
},
}
)
.then(() => {
//this below peace of code isn't important
Event.$emit("dbPropertyChanged");
$("#addPropertyMaxSpeedModal").modal("hide");
Swal.fire({
position: "center",
type: "success",
title: "Nova brzina unešena u bazu",
showConfirmButton: false,
timer: 1500,
});
})
.catch(() => {
Swal.fire("Neuspješno!", "Nešto je pošlo do đavola", "warning");
});
};
Interceptors
I had the same issue and the reason was that I hadn't returned the response in the interceptor. Javascript thought, rightfully so, that I wanted to return undefined for the promise:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});