How to make http GET/POST request in ionic 2? - ionic-framework

How to http GET/POST request in ionic2
and what are the data need to import ?
I tried with HTTP GET request in JavaScript? but it does not work for me.

GET Example
this.posts = null;
this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot').map(res => res.json()).subscribe(data => {
this.posts = data.data.children;
});
console.log(this.posts);
https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/
POST Example
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let body = {
message:"do you hear me?"
};
this.http.post('http://spstest.000webhostap..., JSON.stringify(body), {headers: headers})
.map(res => res.json())
.subscribe(data => {
console.log(data);
});
}
https://www.joshmorony.com/how-to-send-data-with-post-requests-in-ionic-2/
Good luck.

For Creating the request firstly we need to add provider by using this command :-
$ ionic g provider restService
here restService is the ts file name in which we write the below code for making request
load() {
console.log(' RestServiceProvider Load Method fro listing');
let postParams = { param1 : '', param2: '' }
if (this.data) {
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
this.http.post("YOUR URL", postParams)
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
In the above code load() is the method of restService class.this method is help out to make the request .This method is called in your other class like this.
this.restSrvProvider.load().then(data => {
let mydata = data;
});
For more knowledge you may go through the ionic blog the

Related

Ionic 4: Setting native http post headers properly

I'm struggling to find the solution to my problem with ionic native http.
I tried the answer to this post, but still i am getting the same error
this is my code
switchToggle(){
let url = 'https://io.adafruit.com//api/v2/myusername/feeds/my-feed-id/data/';
const headers = new Headers();
headers.set("Content-Type", "application/json")
headers.set("X-AIO-Key", "PASTED_MY_KEY_HERE");
let data = {
"datum":{
"value" : 1
}
};
this.http.setDataSerializer('json');
this.http.post(url,data,{headers:headers})
.then(data => {
console.log(data);
}).catch(error => {
console.log(error)
});
}
and this is the error I am getting
when I try other post request without headers it is working fine. But for this specific API I need to send the request together with the headers.
set your header like this =>
setHeaders() {
let headers = new Headers();
headers.append("X-AIO-Key", "PASTED_MY_KEY_HERE");
headers.append('Content-Type', 'application/json' );
const requestOptions = new RequestOptions({ headers: headers });
return requestOptions;
}
switchToggle(): Observable<any>{
let data = {
"datum":{
"value" : 1
}
};
return this.http.post(url, data, this.setHeaders())
.map(Response => Response.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}

Add default data to Axios request

I am working on a project with React and a Rails API.
In each of my Axios requests, I want to pass a variable to my API.
Can I configure Axios to tell it to add a variable in the data when I try to POST, DELETE, PUT, PATCH…?
Example:
axios.post('url', { data: 'some_data' }).then(...)
→ API should receive:
data_of_request = { data: 'some_data', added_data_from_config_axios: 'some_variable' }
You can create your own function like this.
const sendPost = (url, data = {}, headers = {}) => {
var body = {...data, added_data_from_config_axios: 'some_variable' };
return axios.post(url, body, { headers });
}
And then, you use this function instead of axios
sendPost(url, { data: 'some_data' }).then(res => {
...
});
Finally I found a better answer.
I just used a built-in function of axios:
const added_data_axios = {
'add_data': '..some_data..'
};
const api = axios.create({
transformRequest: [(data) => {
return {...added_data_axios, ...data};
}, ...axios.defaults.transformRequest],
});

cannot retrieve data from angular http

I'm trying to retrieve data from a collection in my mongodb using http module using the code below,
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts').map(res => {
console.log("mapped result",res);
res.json()
});
}
It fails everytime with a response
Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Response.webpackJsonp.../../../http/#angular/http.es5.js.Body.json (http.es5.js:797)
at MapSubscriber.project (auth.service.ts:45)
at MapSubscriber.webpackJsonp.../../../../rxjs/operators/map.js.MapSubscriber._next (map.js:79)
at MapSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89)
at XMLHttpRequest.onLoad (http.es5.js:1226)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:192)
but when I try it with postman, I'm getting the expected result which is this,
I'm returning the response from the service and subscribing its data from a component like this,
ngOnInit() {
this.auth.getPosts().subscribe(data => {
this.value = data.posts;
console.log("blog component",this.value)
},err => {
console.log(err);
})
}
What am I doing wrong? Any help would be much appreciated
You need to convert the response in map and subscribe to it to get the final JSON response
Updated code would look like this-
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts')
.map(res => res.json())
.subscribe((data: any) => {
//console.log(data);
});
}
I hope this helps. :)
Try returning inside the .map()
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts').map(res => {
console.log("mapped result",res);
return res.json()
});
}
}
or drop the brackets (this gives you an implied return),
getPosts() {
return this.http.get('http://localhost:5005/blog/getposts')
.map(res => res.json() );
}
}

Using angular 4 to send form-data

Hi I'm building a WordPress theme and I need to use contact form 7 plugin on it, but I can't figure out the correct way to send the form data to the plugin.
here is my post service:
import {
Injectable
} from '#angular/core';
import {
HttpClient,
HttpHeaders
} from '#angular/common/http';
#Injectable()
export class FormsService {
constructor(private http: HttpClient) {}
postForm(url, form) {
return this.http.post(url, form, {
headers: new HttpHeaders().set('Content-Type', 'multipart/form-data'),
})
}
}
and the component part that use the service:
onSubmit() {
const fd = new FormData();
fd.append('your-name', this.name);
fd.append('your-email', this.email);
fd.append('your-message', this.message);
fd.append('your-subject', this.sumbject);
const url = `/wp-json/contact-form-7/v1/contact-forms/${this.form_id}/feedback`;
this.sendMsg.postForm(url, fd).subscribe(
data => {
console.log(data);
},
err => console.log({
error: err
})
)
this.submitted = true;
}
At this point the server response that the message was submitted ok, but when I go to the WP admin page, non of the field get the values.
But If I use postman with this url and params the form all works as I want.
I also found another solution that works but its not the angular way as I want to be.
the solution
onSubmit() {
const url = `/wp-json/contact-form-7/v1/contact-forms/${this.form_id}/feedback`;
this.submitted = true;
}
sendData(url) {
let XHR = new XMLHttpRequest();
const FD = new FormData();
FD.append('your-name', this.name);
FD.append('your-email', this.email);
FD.append('your-message', this.message);
FD.append('your-subject', this.subject);
// Define what happens on successful data submission
XHR.addEventListener('load', function(event) {
alert('Yeah! Data sent and response loaded.');
});
// Define what happens in case of error
XHR.addEventListener('error', function(event) {
alert('Oups! Something went wrong.');
});
// Set up our request
XHR.open('POST', url);
// Send our FormData object; HTTP headers are set automatically
XHR.send(FD);
}
I found my solution, the problem was on the headers definitions of my service, the correct way is:
postForm(url, body) {
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/form-data');
return this.http.post(url, body, {headers: headers })
}

Passport-jwt issue : JWT token is working with postman but not working with UI api call

I have integrated passport-jwt for authentication purpose. It's working like charm but whenever Frontend guy use it from frontend angular 2 its giving Unauthorised 401 . I've tried alot but not getting any clue, it must be a silly mistake though.
my passport strategy file is as
let JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
//let fromHeader = require('passport-jwt').fromHeader
// load up the user model
const User = require('../components/user/model');
const database = require('./database'); // get db config file
const config = require('./config'); // get db config file
module.exports = function(passport) {
//var passportStrategy = function(passport){
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
//opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("JWT");
console.log("opts.jwtFromRequest==",opts.jwtFromRequest);
opts.secretOrKey = config.secret;//config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
//console.log("opt==",JSON.stringify(opt));
//console.log("jwt_payload===",jwt_payload);
User.findOne({_id: jwt_payload._doc._id}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};
my route is as
app.get("/api/user/getAll",
passport.authenticate('jwt',{session:false}),
userController.fetchUsers
);
And frontend header append is as follows :
logoutUser(token) {
//const userData = JSON.stringify(userInfo);
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', token); //e.g.token = JWT dasddddasdsda
//headers.append('Authentication', token);
console.log(headers)
return this.http.post('http://localhost:9000/api/user/logout', { headers: headers })
.map((response: Response) =〉 {
return response.json()
})
.catch(this.errorHandler);
}
It would really great if anyone can assist me further to identify the mistake.
Second argument for the post method is payload.
so this code below
this.http.post('http://localhost:9000/api/user/logout', { headers: headers })
has to be
this.http.post('http://localhost:9000/api/user/logout', {}, { headers: headers })