How to take a string from JSON in Angular - php

So I basically trying to set a token on my localStorage. I make a request to my API in PHP and this is the code:
login() {
const body = JSON.stringify({
"usuario":"juanma",
"password":"1234"});
console.log(body);
const params = new HttpParams();
const headers = new HttpHeaders();
this.http.post<AuthResponse>("http://localhost:8000/login", body, {'headers':headers,'params':params})
.subscribe(data => localStorage.setItem('token', data.token.toString()));
}
I actually get the token, I even can see it on the console.log (not appears on the code right now, but I tried it and it does appear).
AuthResponse is a model I created that replicates the JSON return from the post method.
However Im not being able to set the token like a string on localStorage, and I get this:
I'm really lost with this. If anyone can help, I'll be thankfull!
EDIT: Added screenshot of the console.log(data.token) inside the subscribe:
EDIT 2: Now I get the token right! Problem is that I need to do the method 2 times in order to make it work.
As you can see, the first time I made the method, it gives the 'undefined' value.

You just need to replace your data.token.toString() to data.token.token
login() {
const body = JSON.stringify({
"usuario":"juanma",
"password":"1234"});
console.log(body);
const params = new HttpParams();
const headers = new HttpHeaders();
this.http.post<AuthResponse>("http://localhost:8000/login", body, {'headers':headers,'params':params})
.subscribe(data => localStorage.setItem('token', data.token.token));
}

Related

POST request does not arrive properly httpClient - ionic - php

I'm creating a REST API in PHP. The service login is:
<?php
include_once 'libs/Database.php';
header("Content-Type: application/json; charset=UTF-8");
Database::getPDO();
$myObj = null;
if ( Database::check($_POST['username'], $_POST['password']) ) {
$myObj = array('message' => "Verified", 'success' => true);
} else {
$myObj = array('message' => "Unauthorized", 'username' => $_POST['username'], 'success' => false);
}
$myJSON = json_encode($myObj);
echo $myJSON;
?>
And as you may see, I'm accessing $_POST global variable.
Postman: sending a POST request with header x-www-form-urlenconded and specifying the keys and values, the server does capture such keys.
Ionic: sending a POST request using HttpClient will not work. (The server captures null for both keys, username and password).
This is the code of the provider:
login(user, pass, url) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
return this.http.post(url, "username="+user+"&"+"password="+pass, httpOptions);
}
I'm wondering how the body should be formatted, and according to this link should be like I have done (username=user&password=pass). By the way, all parameters are not null when the login function is called, hence, the problem is in the request.
For those of you interested, the answer of the server is:
{message: "Unauthorized", username: null, success: false}
Any help will be appreciated.
I'm copying my comment as an answer 'cause I want to post a photo.
Assuming you're using Angular's HttpClient, try to specify which type you're sending via POST: try to do something as this.http.post<string>(url, 'string', opts);.
I also suggest you to take a look at what you're sending as request via Chrome's Inspector (F12 on windows/linux, Cmd+Options+I on Mac), Network tab.
Obviously you must open it before sending request to be captured by DevTools. If you're debugging directly through the phone, on Windows/Linux you can use Remote Devices tab on Chrome's DevTools, or Safari on Mac.
An example using Chrome's DevTools:

Passing return values from php api array to another page

In my ionic app I tried passing array returned from a php api to another page but it was not passing any values
In user.html page I have the button that when click pass the value to the next page
<button ion-button icon-only (click)="goToResult()">
<ion-icon ios="ios-log-out" md="md-log-out" class="user"></ion-icon> Next
</button>
userHome.ts
ngOnInit(){
this.phone = this.navParams.get('phone');
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json' );
let options = new RequestOptions({ headers: headers });
let data = {
phone: this.phone
};
let loader = this.loading.create({
content: 'Loading Page Contents',
});
loader.present().then(() => {
this.http.post('http://mypro.com/eApi/retrieve.php',data, options)
.map(res => res.json())
.subscribe(res => {
loader.dismiss()
this.items=res.server_response;
console.log(this.items);
});
});
//this.navCtrl.push(PostPage, data);
}
On the same page, this is the push nav I tried passing the values through
goToResult(){
console.log(this.items);
this.navCtrl.push(PostPage,
this.postList = this.items
)
}
In post.ts, I added this to the contructor
this.navParams.get(this.postList);
then in my post.html
<ion-title *ngFor="let post of postList">{{post.Name}}
</ion-title>
Please, how can I pass the return values from the api to another page?
Thanks.
So if you check ionic doc example you will see that you need to pass data using json object and use its key to retrieve data, try this approach:
In your first component:
this.navCtrl.push(PostPage,
{ postList: this.items }
)
In receiving component constructor;
this.postList = this.navParams.get(“postList”);
If still struggle please share full code, but this should be easy fix;)
you can do like this
goToResult(){
console.log(this.items);
this.navCtrl.push(PostPage, {postList = this.items})
}
In post.ts, you can get value by
this.navParams.get('postList');

React APP with Laravel Back End, Can not Insert data

I'm learning to build React JS WebApp with Laravel Back End. I have problem when try to insert data, it seems my insert function in controller is not being called whatever method I try. Here is the code;
The JS:
fetch( '/api/links/', {
method:'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(link)
})
.then(response => {
return response.json();
})
.then(data => {
//update the state of links
});
The /routes/api.php:
Route::post('links', 'LinksController#store');
The /app/Http/Controllers/LinksController.php:
public function store(Request $request)
{
$link = new Link;
$link->title = 'Hard Coded Just For Testing';
$link->url = 'http://but.still/not-inserted-to-database/';
$link->save();
return response()->json(null, 200);
}
My expectation there should be a new record in my Links table, but nothing new inserted.
What did I Miss?? Please Help.
UPDATE:
Event though I set the method to post in fetch options, it turns out when I observe in Developer tools - network tabs, it strangely change to GET method, that's why it never get to call my store function to insert data. Does anyone know what causes this?
SOLVED:
It turns out that because of extra '/' at the end of fetch URL, while in routes/api.php the URL does not have '/' at the end of it, that causing a reroute when original call to /api/links/ with POST rerouted to /api/links with GET. SO simply match the URL perfectly from the route and from the fetch, solve the problem.

Pass multiple values with http GET from Angular2 to php

Am using Angular2 as front end and php as my server script . I want to pass the user login details to server with the http.get() .
I used like..
var uname = event.email;
var pass = event.password;
this.http
.get('http://192.168.0.100:80/php/logincheck.php?user='+uname+'&pwd='+pass).subscribe();
but it can't get the 2 values. I can simply pass a single value easily.
If 2 values can be passed like this. Please help ..
I do not think it is secured to send a password without doing some sort of encrypting. but if you want to send some data to your server request it is possible to send them in the request headers as well. see below code snippet.
//on import section
import { Http, Headers, RequestOptions } from '#angular/http';
//inside your login function
let requestUrl= "http://192.168.0.100:80/php/logincheck.php"
let requestOptions = new RequestOptions();
requestOptions.headers = new Headers({ 'Content-Type': 'application/json', 'email': event.email,
'pwd': event.password });
this.http.get(requestUrl, this.requestOptions).subscribe();
Try like this :
import { URLSearchParams, BaseRequestOptions } from '#angular/http';
getLogin() {
const options: BaseRequestOptions = new BaseRequestOptions();
const params: URLSearchParams = new URLSearchParams();
params.set('uname', event.email);
params.set('pass', event.password);
options.search = params;
return this.http.get('http://192.168.0.100:80/php/logincheck.php', options)
.map(res => res.json())
}
Server side :
<?php
echo $_GET['uname'];
?>
or
$url = parse_url($url);
parse_str($url['query'], $queryParams);
echo $queryParams['uname'];
echo $queryParams['pass'];

Ionic2 / Angular2 MailChimp API GET response

Okey so I've got a little problem with MailChimp response. So here is the thing.
I want to check the status of the subscribed user. I have the PHP code which is works fine and i have the code which is also works fine so I get the response BUT I can't use the response after it. So here is the codes:
I have a MailService provider which contain this function:
postCheck(post: {email: string}): Observable<any>{
const email = JSON.stringify(post);
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-urlencoded');
return this.http.post('http://localhost:8100/getapi', email, {
headers: headers
}).map(res => {
console.log(res.json())
return res.json(); //add this line
});
}
In the main page I have this function:
sendCheck(email: string){
this.mailservice.postCheck({email: email})
.subscribe(
response => this.response = response.status,
error => console.log(error)
);
}
In the main page html when i call <p>{{ response }}</p> it write out 'pending' or 'subscribed'. But after it when I try console.log(this.response); it write out nothing so in the code I can't really do the checking.
From what I can gather, you want to do something with your response after the data has arrived. This you need to do inside the subscription, to ensure that the data is available. So something like this:
sendCheck(email: string){
this.mailservice.postCheck({email: email})
.subscribe(response => {
this.response = response.status;
// here the value has been set to response, so do what you want
this.doSomethingWithResponse();
)};
}
doSomethingWithResponse() {
if(this.response == 'subscribed') {
// do stuff
}
}

Categories