I have some trouble with my Http Post Request in Flutter. I must connect to a PHP web service (using a header) and post some user/password info to get a response (here, user info).
I believe I am near to the solution but I still get a StatusCode 401 as response despite the fact that it works when I try with Postman (with same credentials).
Here is the code of the function I call :
Future<http.Response> post() async {
var url = "https://www.monadresse/login.php";
String password = "xxx";
String username = "yyy";
//var bytes = utf8.encode("$username:$password");
var bytes = "$username:$password";
String userNameUser = "www";
String passwordUser = "zzz";
var passwordUserEncoded = base64.encode(utf8.encode(passwordUser));
//var passwordUserEncoded = base64.encode(passwordUser);
var headers = {
"Authorization": "Basic $bytes",
"Content-Type": "application/json",
};
var requestBody = json.encode({ 'user': userNameUser, 'password': passwordUserEncoded});
print(headers);
print(requestBody);
final http.Response response = await http.post(
url,
body: requestBody,
headers: headers,
);
if(response.statusCode == 200){
var responseJson = json.decode(response.body);
print(Utf8Codec().decode(response.bodyBytes));
print("Body: " + responseJson);}
print(bytes);
print(passwordUserEncoded);
print(response.statusCode);
print("Fini");
}
Another weird thing (read 'I don't understand')... I have added some prints to have an idea of what's happening and, as you can see hereunder, the 2 first prints (located before the request) are first printed twice and after that the 3 last prints are also repeated twice.
flutter: {Authorization: Basic yyy:xxx, Content-Type: application/json}
flutter: {"user":"www","password":"zzz"}
flutter: {Authorization: yyy:xxx, Content-Type: application/json}
flutter: {"user":"www","password":"zzz}
flutter: yyy:xxx
flutter: zzz
flutter: 401
flutter: Fini
flutter: yyy:xxx
flutter: zzz
flutter: 401
flutter: Fini
As I don't find a solution on the net I very hope someone will help me.
As mentioned in the comments, the cause of this issue is that the 'username:password' used in the authorization header isn't encoded to base64.
Here's a working sample for basic authentication using test endpoints from Postman. The username is postman and the password is password.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' show utf8, base64;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
var _usernameTextController = TextEditingController();
var _passwordTextController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Container(
padding: EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
controller: _usernameTextController,
decoration: const InputDecoration(
labelText: 'Username',
),
),
TextFormField(
controller: _passwordTextController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Password',
),
),
ElevatedButton(
child: Text('Login'),
onPressed: _doLogin(_usernameTextController.text, _passwordTextController.text),
)
],
),
),
),
);
}
_doLogin(String username, String password) {
if (username.trim().isEmpty || password.trim().isEmpty) {
debugPrint('Either username or password is empty');
} else {
_login(username, password)
.then((value) => debugPrint('Login finished $value'))
.catchError((error) => debugPrint('Login error: $error'));
}
}
Future _login(String username, String password) async {
// 'username:password' is base64 encoded
var authHeader = '${base64.encode(utf8.encode('$username:$password'))}';
debugPrint('userpass: ${username + password}');
debugPrint('authHeader: $authHeader');
final response = await http.get(
'https://postman-echo.com/basic-auth',
headers: {HttpHeaders.authorizationHeader: "Basic $authHeader"},
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return response.body;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception(
'Failed to login [${response.statusCode}] ${response.body}');
}
}
}
Related
This is how I picked a file from device
onPressed: () async {
FilePickerResult? result =
await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: [
'jpg',
'pdf',
'doc'
],
);
List<File> files = result!.paths
.map((path) => File(path!))
.toList();
context
.read<Dropper>()
.fileCheck(result: result);
myfile = files[0];
},
Then I Converted to Uint8List :
Uint8List imgbytes = await myFile.readAsBytes();
Now I am sending that file to Php database
final url = "http://10.0.2.2:8000/api/addSurvey";
final uri = Uri.parse(url);
final response = await api.post(uri, headers: {
'Authorization': token,
}, body: {
"bill_image": imgbytes
}
It throws error msg like this : type 'Uint8List' is not a subtype of type 'String' in type cast
var url = "http://10.0.2.2:8000/api/addSurvey";
Map<String, String> headers = {"Content-Type": "application/json",
'Authorization': token,};
var request = http.MultipartRequest("POST", Uri.parse(url));
if(_image != null){
var pic = await http.MultipartFile.fromBytes('bill_image', imgbytes , filename: 'photo.jpg');
request.files.add(pic);
}
request.send().then((result) async {
http.Response.fromStream(result).then((response) async {
if (response.statusCode == 200)
{
}
else{
}
return response.body;
});
}).catchError((err) => print('merror : '+err.toString())).whenComplete(()
{
});
Try it using multipart request.
if php is accepting parameter as file type File then you need to send image as multipart request i guess.
var headers = {
'Authorization': 'token'
};
var request = http.MultipartRequest('POST', Uri.parse('http://10.0.2.2:8000/api/addSurvey'));
request.files.add(await http.MultipartFile.fromPath('bill_image', 'path to your file'));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
I am trying to make a request to a PHP server from my swift app. For some reason php is showing an empty array as the $_REQUEST variable. I have looked through stack overflow and implemented everything I can find that might help, but still getting an empty array in php. Here is the relevant swift code...
func connect(_ pin: String, completion: #escaping(Result<ConnectResponse?, Error>) -> ()) {
let params: [String : Any] = [
"mobile_pin_connect": pin,
"device_info": UIDevice().model,
"additional_info": UIDevice().systemVersion
]
doRequest(params: params) { (data) in
if let data = data {
do {
let res = try JSONDecoder().decode(Dictionary<String, String>.self, from: data)
completion(.success(
ConnectResponse(success: (res["success"] == "true"), connect_id: res["connect_id"] ?? nil, error: res["error"] ?? nil)))
} catch {
completion(.failure(error))
}
} else {
print("in else block")
}
}
}
fileprivate func doRequest(params: [String: Any], completion: #escaping (Data?) -> ()) {
let body = createJsonBody(params)!
self.request.httpBody = body
print("Sending request with thw following variables")
print(String(data: body, encoding: .utf8)!)
print(String(data: self.request.httpBody!, encoding: .utf8))
URLSession.shared.dataTask(with: self.request) { (data, response, error) in
if let error = error {
print("Error in request: \(error)")
completion(nil)
}
let stringResult = String(data: data!, encoding: .utf8)!
let properResult = String(stringResult.map {
$0 == "." ? "=" : $0
})
let decodedData = Data(base64Encoded: properResult)
completion(decodedData)
}.resume()
}
fileprivate func createJsonBody(_ params: [String: Any]) -> Data? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: params)
let body = Data(jsonData).base64EncodedData()
return body
} catch {
print("Unable to create json body: " + error.localizedDescription, error)
return nil
}
}
That sends the request to the server, the setup for the request is in the static var setup...
private static var sharedConnector: ApiConnector = {
let url = URL(string: "https://mywebsiteURLhere.com/api/mobile/challenge")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let connector = ApiConnector(request)
return connector
}()
So I have the right header values for application/json I have the request method set to post, I am base64encoding the json data and in PHP I have the setup getting php://input...
$rawRequest = file_get_contents("php://input");
and dumping the $_REQUEST variable to an error log, but I always get array\n(\n)\n
it is just showing an empty array
I even did
error_log("Raw request from index.php");
error_log(print_r($rawRequest, true));
and it logs a completely empty line.
I can't figure out why PHP is getting nothing in the request, from everything I have seen online I am doing the request correctly in swift. Any help is really appreciated. Thank you
As per your Swift Code, Can you please replace the following method.
fileprivate func createJsonBody(_ params: [String: Any]) -> Data? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: params)
let body = Data(jsonData)
return body
} catch {
print("Unable to create json body: " + error.localizedDescription, error)
return nil
}
}
You need to replace this line let body = Data(jsonData) with
let body = Data(jsonData).base64EncodedData()
Without seeing your PHP code, it is difficult to determine the entire picture. However, whatever steps you perform to encode your data via the client (Swift) you must reverse to successfully decode the message on the server.
For example, if you prepare and send the request from your client as follows.
Client:
JSON encode data
base-64 encode
send data
The your server must reverse the steps to successfully decode the data.
Server:
recv data
base-64 decode data
JSON decode data
Unless your server requires it, I would remove the base-64 encode step, as it only complicates your encode / decode process.
I have created a working example: https://github.com/stuartcarnie/stackoverflow/tree/master/q59329179
Clone it or pull down the specific code in your own project.
To test, open up a terminal and run the php server:
$ cd q59329179/php
$ php -S localhost:8080 router.php
PHP 7.3.9 Development Server started at Thu Dec 19 10:47:58 2019
Listening on http://localhost:8080
Document root is /Users/stuartcarnie/projects/stackoverflow/q59329179/php
Press Ctrl-C to quit.
Test it works with curl in another terminal session:
$ curl -XPOST localhost:8080 --data-binary '{"string": "foo", "number": 5}'
Note you should see output in the php session:
[Thu Dec 19 11:33:43 2019] Array
(
[string] => foo
[number] => 5
)
Run the Swift test:
$ cd q59329179/swift
$ swift run request
Note again, decoded output in php session:
[Thu Dec 19 11:20:49 2019] Array
(
[string] => string value
[number] => 12345
[bool] =>
)
Your request is probably not arriving through the POST structure, but is kept in the request body.
Try running this as your first PHP operation:
$raw = file_get_contents('php://input');
and see what, if anything, is now into $raw. You should see a Base64 encoded string there, that you need to decode - like this, if you need an array:
$info = json_decode(base64_decode($raw), true);
I've tested your code and it's working fine. The issue might be at your PHP end. I've tested the following code on local server as well as on httpbin
The output from a local server (recent version of XAMPP (php 7.3.12)):
Sending request with thw following variables
eyJhZGRpdGlvbmFsX2luZm8iOiIxMy4yLjIiLCJtb2JpbGVfcGluX2Nvbm5lY3QiOiIxMjM0IiwiZGV2aWNlX2luZm8iOiJpUGhvbmUifQ==
result eyJhZGRpdGlvbmFsX2luZm8iOiIxMy4yLjIiLCJtb2JpbGVfcGluX2Nvbm5lY3QiOiIxMjM0IiwiZGV2aWNlX2luZm8iOiJpUGhvbmUifQ==
message ["additional_info": "13.2.2", "mobile_pin_connect": "1234", "device_info": "iPhone"]
Code:
ApiConnector.swift
import Foundation
import UIKit
class ApiConnector{
var request: URLRequest
private init(request: URLRequest) {
self.request = request
}
public static var sharedConnector: ApiConnector = {
let url = URL(string: "http://localhost/post/index.php")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let connector = ApiConnector(request: request)
return connector
}()
func connect(_ pin: String, completion: #escaping(Result<Dictionary<String, String>, Error>) -> ()) {
let params: [String : Any] = [
"mobile_pin_connect": pin,
"device_info": UIDevice().model,
"additional_info": UIDevice().systemVersion
]
doRequest(params: params) { (data) in
if let data = data {
do {
let res = try JSONDecoder().decode(Dictionary<String, String>.self, from: data)
completion(.success(res))
} catch {
completion(.failure(error))
}
} else {
print("in else block")
}
}
}
fileprivate func doRequest(params: [String: Any], completion: #escaping (Data?) -> ()) {
let body = createJsonBody(params)!
self.request.httpBody = body
print("Sending request with thw following variables")
print(String(data: body, encoding: .utf8)!)
URLSession.shared.dataTask(with: self.request) { (data, response, error) in
if let error = error {
print("Error in request: \(error)")
completion(nil)
}
let stringResult = String(data: data!, encoding: .utf8)!
print("result \(stringResult)")
let properResult = String(stringResult.map {
$0 == "." ? "=" : $0
})
let decodedData = Data(base64Encoded: properResult)
completion(decodedData)
}.resume()
}
fileprivate func createJsonBody(_ params: [String: Any]) -> Data? {
do {
let jsonData = try JSONSerialization.data(withJSONObject: params)
let body = Data(jsonData).base64EncodedData()
return body
} catch {
print("Unable to create json body: " + error.localizedDescription, error)
return nil
}
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
let session = URLSession.shared
override func viewDidLoad() {
super.viewDidLoad()
ApiConnector.sharedConnector.connect("1234") { (result) in
switch result {
case .success(let message):
print("message \(message)")
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
index.php
echo file_get_contents("php://input");
You can verify your code by doing a request to https://httpbin.org/post
output:
Sending request with thw following variables
eyJkZXZpY2VfaW5mbyI6ImlQaG9uZSIsImFkZGl0aW9uYWxfaW5mbyI6IjEzLjIuMiIsIm1vYmlsZV9waW5fY29ubmVjdCI6IjEyMzQifQ==
result {
"args": {},
"data": "eyJkZXZpY2VfaW5mbyI6ImlQaG9uZSIsImFkZGl0aW9uYWxfaW5mbyI6IjEzLjIuMiIsIm1vYmlsZV9waW5fY29ubmVjdCI6IjEyMzQifQ==",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-us",
"Content-Length": "108",
"Content-Type": "application/json; charset=utf-8",
"Host": "httpbin.org",
"User-Agent": "SessionTest/1 CFNetwork/1120 Darwin/19.0.0"
},
"json": null,
"origin": "122.173.135.243, 122.173.135.243",
"url": "https://httpbin.org/post"
}
in else block
If you are running an older version of PHP then You might need HTTP_RAW_POST_DATA
Have look at this SO for more info on PHP side.
I have an "api rest" that I created in PHP, the service returns a JSON with the parameters of "header", "body", "get", "pos", which comes to receive without any type of validation.
Now I have created a service in angular to connect with the "api rest", all right up there, the problem I have is that I want to send a parameter as a "BODY", but I do not know how, I have been investigating but I have not found a shape.
Is it possible to send the "body" via HttpClient.get()?
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ServicioService {
constructor(private http: HttpClient) { }
getQuery(query: string){
const url = `http://localhost:8080/servicio/`;
const headers = new HttpHeaders({
'Authorization': 'Bearer BQAiaibx-we0RSlZFN29B5TPF4t6egxbuuEsc5ZYZhpamHUhImd5'
});
const params = new HttpParams()
.set('page', '2')
.append('page', '3')
.set('sort', 'abc');
return this.http.get (url, { params, headers});
}
getNewReleases(){
return this.getQuery("")
.pipe( map((data: any) => {
return data;
}));
}
}
A GET request does not have a body.
You should use POST or PUT.
You can read here a little bit about the http methods.
About the GET: The GET method requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect
So, it would be wrong to send a body because a GET method should not change anything.
I need to know how to pass parameters between angular 7 and a PHP API
import { Injectable } from '#angular/core';
import { HttpClient, HttpParams } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getUsers() {
return this.http.get('http://localhost/backend/json/data_products.php');
}
getProduct(productId) {
const params = new HttpParams().set('id', productId);
return this.http.get('http://localhost/backend/json/data_product.php/', {params});
}
}
but I got this error
core.js:12584 ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK
Please refer to Angular doc: https://angular.io/api/common/http/HttpClient#get
get(url: string, options: { headers?: HttpHeaders | { [header:
string]: string | string[]; }; observe?: "body"; params?: Ht...)
It should be like:
this.http.get('http://localhost/backend/json/data_product.php/', { params: params });
in your case.
I think you need to pass header in request like below.May be this is help you.
update(id: number, data: any){
let model = JSON.stringify(data);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.put( 'http://localhost/backend/json/data_product.php/'+id,model, options);
}
Can you tell me where I'm wrong? When I use the Postman then it's working.But why I cannot do the same using Angular2? Here the backend api is from PHP.I have never used PHP backend before.Is that different than normal ASP.net Web Api? I mean the way we have to send the parameters and all...
Service.ts
import { Injectable } from '#angular/core';
import { Http, RequestOptions, Headers, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
#Injectable()
export class AuthenticationData {
authenticationEndPoint: string = "https://www.myk.com/admin/index.php?route=api/login";
constructor(public http: Http) {
}
//to login
loginUser(username: string, password: string): Observable<any> {
let headers = new Headers();
headers.append('content-type', 'application/json');
/*let body = {
username: username,
password: password,
}*/ Not working this too :(
let body='username=myname&password=admin';//I tried hardcode value.But not working
let options = new RequestOptions({ headers: headers });
return this.http.post(this.authenticationEndPoint, body, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
login.ts
//to login
loginUser(): void {
if (this.loginForm.valid) {
this.authenticationData.loginUser(this.loginForm.value.username, this.loginForm.value.password).subscribe(
data => {
this.response = data;
},
err => {
console.log(err);
},
() => console.log('Complete')
);
}
}
Error:
body: "{"error":"Invalid Request type","status":"201"}", status: 200,
ok: true, statusText: "OK",
Php:
<?php
class ControllerApiLogin extends Controller {
private $error = array();
public function index() {
$json = array();
if (($this->request->server['REQUEST_METHOD'] == 'POST') && !empty($this->request->get['username']) && !empty($this->request->get['password'])) {
if(!empty($this->request->get['username']) && !empty($this->request->get['password'])){
$this->load->language('common/login');
$this->document->setTitle($this->language->get('heading_title'));
// User
$this->registry->set('user', new Cart\User($this->registry));
if ($this->validate()) {
$token = token(32);
$token_count = $this->user->getUniqueToken($token);
if($token_count==0)
{
$this->session->data['token'] = $token;
}else{
$token = token(32);
$token_count = $this->user->getUniqueToken($token);
$this->session->data['token'] = $token;
}
$this->load->model('user/user');
$user_info = $this->model_user_user->getUserByEmail($this->request->get['username']);
$tokeninfo = array();
if(count($user_info) > 0){
$tokeninfo = array(
'token' => $token,
'user_id' => $user_info['user_id'],
'ip' => $this->request->server['REMOTE_ADDR']
);
$date_expired = $this->model_user_user->addUserapitoken($tokeninfo);
}else{
$date_expired = '';
}
$json['token'] = $token;
$json['date_expired'] = $date_expired;
$json['status'] = '200';
}else{
$json['error'] = "No match for Username and/or Password.";
$json['status'] = '201';
}
}else{
$json['error'] = 'Something Went Wrong!!! <br> PLease Enter Correct Login Credentials!!!';
$json['status'] = '201';
}
//$this->response->addHeader('Content-Type: application/json');
//$this->response->setOutput(json_encode($json));
}
else{
$json['error'] = 'Invalid Request type';
$json['status'] = '201';
}
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->addHeader('HTTP/1.1'.$json['status']);
$this->response->setOutput(json_encode($json));
}
protected function validate() {
//$this->registry->set('user', new Cart\User($this->registry));
if (!isset($this->request->get['username']) || !isset($this->request->get['password']) || !$this->user->login($this->request->get['username'], html_entity_decode($this->request->get['password'], ENT_QUOTES, 'UTF-8'))) {
$this->error['warning'] = $this->language->get('error_login');
}
return !$this->error;
}
}
OP's feedback: I have to use it like this.Cheers :)
authenticationEndPoint: string = "https://www.myk.com/admin/index.php?route=api/login&username=";
loginUser(username: string, password: string): Observable<any> {
let headers = new Headers();
headers.append('content-type', 'application/json');
let body = '';
let options = new RequestOptions({ headers: headers });
let url = this.authenticationEndPoint + encodeURI(username) + '&password=' + encodeURI(password);
return this.http.post(url, body, options)
.map(this.extractData)
.catch(this.handleError);
}
Original Answer:
headers.append('content-type', 'application/json');
let body='username=myname&password=admin';//I tried hardcode value.But not working
You seem to be setting content type as json. So your body needs to be set as an object. Do:
let body ={
username:myname,
password:admin
}
And then send the request. It should convert this to json and send.
return this.http.post(this.authenticationEndPoint, body, options)
.map(this.extractData)
.catch(this.handleError);
Seems like you want to use URLSearchParams instead, and send the data as x-www-form-urlencoded instead of JSON. The URLSearchParams will encode the parameters as you have tried when hardcoding, but I think your problem is when you are trying to send it as JSON, send it as x-www-form-urlencoded instead. So try this:
import { URLSearchParams } from '#angular/http';
loginUser(username: string, password: string): Observable<any> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let body = new URLSearchParams();
body.set('username',username);
body.set('password',password)
let options = new RequestOptions({ headers: headers });
return this.http.post(this.authenticationEndPoint, body.toString(), options)
.map(this.extractData)
.catch(this.handleError);
}
//you need to import this
import { Http, Headers, URLSearchParams, Request, RequestOptions, RequestMethod } from '#angular/http';
this.body= {
"username":myname,
"password":admin
} //body is defined here
let headers = new Headers();
headers.append('HeaderKey', headerValue);
let options = new RequestOptions({
method: RequestMethod.Post,
url: this.authenticationData.loginUser(this.loginForm.value.username, this.loginForm.value.password),
body: this.body,
headers: headers
});
//here you are making request
this.http.request(new Request(options))
.map(res => res.json())
.subscribe(data => {
//data is fetched
if(data.code==200){
this.response = data;
}
else{
console.log("some issue with the api response")}
}, err => {
console.log("ERROR!: ", err);
});
May be this way things will work for you