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'];
Related
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));
}
I'm using axios in Reactjs to send user's data to php and then create a new user with php,but when I want to send my data it goes empty and my php side gives some error
My react codes
import React, { useReducer } from 'react';
import axios from 'axios';
import UserContext from './userContext';
import userReducer from './userReducer';
//Register user
const registerUser = async () =>{
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const response = await axios.post('http://localhost/react_cms/api/users/user.php' , {message : 'ppp'} , config);
console.log(response.data);
}
return (
<UserContext.Provider
value={{
registerUser
}}>
{props.children}
</UserContext.Provider>
);
}
export default UserState;
And my php side codes :
<?php
$message = isset($_GET['message']) ? $_GET['message'] : 'no';
$data = array ('message' => $message);
echo json_encode($data);
?>
The result of this code is :
{message : 'no'}
You have to either change this line
$message = isset($_GET['message']) ? $_GET['message'] : 'no';
into
$message = isset($_POST['message']) ? $_POST['message'] : 'no';
or leave it as it is and send a get request by changing your axios call
from
const response = await axios.post('http://localhost/react_cms/api/users/user.php' , {message : 'ppp'} , config);
to
const response = await axios.get('http://localhost/react_cms/api/users/user.php?message=ppp', config);
Please note that the signature of the get method is different than the post method in Axios, as the get method does not require the data parameter.
It's considered good practice to when sending data to store you use the POST verb, whereas if you are retrieving data for a certain identifier, you may use GET.
Have a look at this documentation for explanations of http verbs that axios can utilize: https://restfulapi.net/http-methods/.
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');
problem
i tried with $request->request->all() //var_dump output:array(0){}
symfony code
public function registerAction(Request $request) {
var_dump($request->request->all());die;
}
Angular2 service
export class UserRegistrationService {
constructor(private http: Http) { }
private headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'});
private insertdataUrl =
'http://localhost/abc/web/app_dev.php/api/v1/register-user';
/* create new user */
create(name: string): Promise<UserDetails> {
return this.http
.post(this.insertdataUrl, JSON.stringify({name: name}), {headers: this.headers})
.toPromise()
.then(res => res.json().data as UserDetails)
.catch(this.handleError);
}
FormData
{"name{"email":"abc#gmail.com","username":"abc","password":"","repeatpassword":""}}:
solution that works
$data = json_decode(file_get_contents('php://input'), true);
// able to get paramters //get,or //post
can anyone suggest why request doesn't print some values.
here im posting form from angular2.
Symfony uses different containers for Post and Get. Try this way.
# Post
$request->request->all()
# Get
$request->query->all()
solution that worked for me
i changed headers
from
private headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'});
To
private headers=new Headers({ 'Content-Type': 'application/json' });
now im able to recieve data.
While I'm experimenting with angular2 a small obstacle came up:
I have php code witch returns chunks of responses using "ob_flush".
In the front end I successfully made "xhr=XMLHttpRequest" requests and received the responses and handle it using "xhr.onprogress()" and "xhr.onreadystatechange()".
Now when I tried to get the same functionality using angular2 http.get(), I couldn't output the results as they arrive from the server! instead the results are shown by angular at the end of the process after receiving the last response.
I think the rxjs Observer object is buffering the responses!.
So how can I change this behavior?
here is my php code, testing.php:
echo date('H:i:s')." Loading data!";
ob_flush();
flush();
sleep(5);
echo "Ready to run!";
here is my angular2 code:
template: `
<div>
<h3>experimenting!</h3>
<button (click)="callServer()">run the test</button>
<div>the server says: {{msg}}</div>
</div>`
export class AppComponent {
msg:any;
constructor (private http:Http){}
callServer(){
this.http.get("localhost/testing.php")
.subscribe(res=> this.msg= res.text());
}
}
When I run this code it shows after 5 seconds:
(19:59:47 Loading data!Ready to run!).
It should instantly output: (19:59:47 Loading data!).
Then after 5 seconds replaces the previous message with:(Ready to run!)
You need to extend the BrowserXhr class to do that in order to configure the low level XHR object used:
#Injectable()
export class CustomBrowserXhr extends BrowserXhr {
constructor(private service:ProgressService) {}
build(): any {
let xhr = super.build();
xhr.onprogress = (event) => {
service.progressEventObservable.next(event);
};
return <any>(xhr);
}
}
and override the BrowserXhr provider with the extended:
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(BrowserXhr, { useClass: CustomBrowserXhr })
]);
See this question for more details:
Angular 2 HTTP Progress bar
After studying rxjs and reading Angular2 source code, I came up with this solution
I found it's better to make custom_backend, I think this is the recommended approach by angular Dev team.
my_backend.ts
import {Injectable} from "angular2/core";
import {Observable} from "rxjs/Observable";
import {Observer} from "rxjs/Observer";
import {Connection,ConnectionBackend} from "angular2/src/http/interfaces";
import {ReadyState, RequestMethod, ResponseType} from "angular2/src/http/enums";
import {ResponseOptions} from "angular2/src/http/base_response_options";
import {Request} from "angular2/src/http/static_request";
import {Response} from "angular2/src/http/static_response";
import {BrowserXhr} from "angular2/src/http/backends/browser_xhr";
import {Headers} from 'angular2/src/http/headers';
import {isPresent} from 'angular2/src/facade/lang';
import {getResponseURL, isSuccess} from "angular2/src/http/http_utils"
export class MyConnection implements Connection {
readyState: ReadyState;
request: Request;
response: Observable<Response>;
constructor(req: Request, browserXHR: BrowserXhr, baseResponseOptions?: ResponseOptions) {
this.request = req;
this.response = new Observable<Response>((responseObserver: Observer<Response>) => {
let _xhr: XMLHttpRequest = browserXHR.build();
_xhr.open(RequestMethod[req.method].toUpperCase(), req.url);
// save the responses in array
var buffer :string[] = [];
// load event handler
let onLoad = () => {
let body = isPresent(_xhr.response) ? _xhr.response : _xhr.responseText;
//_xhr.respons 1 = "Loading data!"
//_xhr.respons 2 = "Loading data!Ready To Receive Orders."
// we need to fix this proble
// check if the current response text contains the previous then subtract
// NOTE: I think there is better approach to solve this problem.
buffer.push(body);
if(buffer.length>1){
body = buffer[buffer.length-1].replace(buffer[buffer.length-2],'');
}
let headers = Headers.fromResponseHeaderString(_xhr.getAllResponseHeaders());
let url = getResponseURL(_xhr);
let status: number = _xhr.status === 1223 ? 204 : _xhr.status;
let state:number = _xhr.readyState;
if (status === 0) {
status = body ? 200 : 0;
}
var responseOptions = new ResponseOptions({ body, status, headers, url });
if (isPresent(baseResponseOptions)) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
let response = new Response(responseOptions);
//check for the state if not 4 then don't complete the observer
if(state !== 4){
//this will return stream of responses
responseObserver.next(response);
return;
}
else{
responseObserver.complete();
return;
}
responseObserver.error(response);
};
// error event handler
let onError = (err: any) => {
var responseOptions = new ResponseOptions({ body: err, type: ResponseType.Error });
if (isPresent(baseResponseOptions)) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
responseObserver.error(new Response(responseOptions));
};
if (isPresent(req.headers)) {
req.headers.forEach((values, name) => _xhr.setRequestHeader(name, values.join(',')));
}
_xhr.addEventListener('progress', onLoad);
_xhr.addEventListener('load', onLoad);
_xhr.addEventListener('error', onError);
_xhr.send(this.request.text());
return () => {
_xhr.removeEventListener('progress', onLoad);
_xhr.removeEventListener('load', onLoad);
_xhr.removeEventListener('error', onError);
_xhr.abort();
};
});
}
}
#Injectable()
export class MyBackend implements ConnectionBackend {
constructor(private _browserXHR: BrowserXhr, private _baseResponseOptions: ResponseOptions) {}
createConnection(request: Request):MyConnection {
return new MyConnection(request, this._browserXHR, this._baseResponseOptions);
}
}
In the main component we have to provide the custom bakend like this:
providers: [
HTTP_PROVIDERS,
PostSrevice,
MyBackend,
provide(XHRBackend, {useExisting:MyBackend})
]
Now when we use http.get() it will return a stream of Observable