I’m using express as my back-end and I want to simply post JSON to it. I can get the request to the server but when it arrives it’s empty and I can’t find my data… Here is my code:
import {Injectable} from "@angular/core";
import { HTTP } from '@ionic-native/http';
import {User} from "./user";
import {Config} from "../config";
import {Observable} from "rxjs/Rx";
import 'rxjs/add/operator/map';
@Injectable()
export class UserService {
constructor(private _http: HTTP) {}
//Makes http request to valid username and password
login(user: User) {
//Creates header to tell server that it is getting json
//Sets address to request
var address = Config.apiUrl + "login/";
//Creates JSON object that contains the data
let data = JSON.stringify({
username: user.username,
password: user.password
});
console.log(data);
//Make request to server
return this._http.post(address, data, {"Content-Type":"application/json"})
.then(res => {
return(res);
})
.catch(error => {
return Observable.throw(error);
})
}
}
Thank you! I’d also like to note that I’ve seen other people say that changing the header to x-www-form-urlencoded will fix it, but I want to send my information with JSON as I plan on using JSON web tokens in the future.
Ok, got it., thank you! After switching over to angular http it still isn’t working though… The server is getting the request but no header or data… I’m running the app on the iOS simulator and I’ve already tried editing the AppDelegate.m file. Thank you again!
import {Injectable} from "@angular/core";
import {Http, Headers, Response} from "@angular/http";
import {User} from "./user";
import {Config} from "../config";
import {Observable} from "rxjs/Rx";
import 'rxjs/add/operator/map';
@Injectable()
export class UserService {
constructor(private _http: Http) {}
//Makes http request to valid username and password
login(user: User) {
//Creates header to tell server that it is getting json
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = { headers: headers };
//Sets address to request
var address = Config.apiUrl + "login/";
//Creates JSON object that contains the data
let data = JSON.stringify({
username: user.username,
password: user.password
});
//Make request to server
return this._http.post(address, data, options)
.map(res => {
return(res);
})
.catch(error => {
return Observable.throw(error);
})
}
I’d also like to mention that I am calling this method like this:
this._userService.login(this.user)
.subscribe((res: any) => {
//Do stuff if status code is 2XX
},
res => {
//Do stuff if status code is 5XX
}
I fixed it! It ended up being the CORS issue… I had read about it but thought that because the server was getting a POST and not OPTIONS I was good, but after inspecting the request I noticed that it was in fact sending OPTIONS… I litterally added two lines of code to my express server and it fixed the issue!
@Bryt12 was you able to change the Content-Type header to application/json? For sure you had other problems before, because in our case you don’t had data in post, we have data in our post but it is in application/x-www-form-urlencoded form and the data is something like that password=b&username=a.
But we are not able to send a json. As described in many post it seems it doesn’t support json format and there are another fork which does.
@Sujan12 BTW and in IMO, on other posts some other team member / moderator wrote to use IonicNative because on mobile devices it should the preferred method because it is many times faster.
Simplicity trumps minimal performance gains, see your current problem But to discuss this (Ionic Native HTTP vs Angular HTTP) please open a new topic. I would be interested in seeing these team member quotes collected and linked to in one place.
I would like prefer using angulars HTTP, but why I have to use Ionic Native?? Because Android System WebView on post using http lib sets Origin header to file:// and our 3rd part libs as really many many others don’t allow Origin file://
So we can not use angulars http because WebView is setting origin and we can not use ionic native because it is not handling json posts? Really?
I won’t reply to all this here in this hijacked topic. If you want to talk about this, as I said, please create a new topic on Ionci Native http vs Angular Http.
I also wrote you on a GitHub issue with cookies. I wanted to add some details, and noticed that it may be better I post it in Ionic forum. So here, the same question with more details:
May I ask how do you make the requests so that the cookies are sent? I cannot get it simply work.
I make a post request to the backend server with the credentials and I can see in the backend logs that the session successfully opened. But the subsequent requests returns that the user is not logged in.
The same code works using angular http, but we need SSL-Pinning, so we must use native http.
I don’t know what I’m missing.
My code looks like as follows (unrelated parts removed):
constructor(public http: HTTP) { }
public get(url, params?: any, options: any = {}) {
let responseData = this.http.get(url, params, {})
.then(resp => options.responseType == 'text' ? resp.data : JSON.parse(resp.data));
return Observable.fromPromise(responseData);
}
public post(url, params?: any, options: any = {}) {
let responseData = this.http.post(url, params, {})
.then(resp => options.responseType == 'text' ? resp.data : JSON.parse(resp.data));
return Observable.fromPromise(responseData);
}
public login(credentials) {
let url = 'https://example.com/login';
return this.post(url, credentials, {responseType: 'text'})
}
public getData() {
let url = 'https://example.com/v1/data';
return this.get(url);
}
After login() function is called, I can see on the server-side that the user is successfully logged in. But subsequent getData() function calls still return a response that the user is not logged in.