What is the equavalent of php getallheaders() function in Angular 4/5 ?
I need to get request headers but i can't find this in Angular. I can get only response headers with Angular.
I need to get request header parameters when application start not sending get or post request. In picture i need X-MSISDN and X-IMSI parameters
I try Interceptor class but its only works when i send get or post requests.
Explanation:
I open application with this url : http://localhost:4200/#/
In this time my request header is like this:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: no-cache
Connection: keep-alive
Cookie: s_fid=07C355F600B90B3D-291EBB86E5858A2F; s_cc=true; gdslv_s=Less%20than%201%20day; s_vnum=1556196774798%26vn%3D7; s_invisit=true; s_ppvl=login%2520sayfasi%2C100%2C100%2C933%2C375%2C667%2C375%2C667%2C2%2CLP; s_ppv=Welcome%253Atarife%253Aanasayfa%2C100%2C100%2C667%2C375%2C667%2C375%2C667%2C2%2CP; s_ppn=Welcome%3Atarife%3Aanasayfa; gdslv=1524831169979; s_getNewRepeat=1524831169981-Repeat; utag_main=v_id:0162fcdd2735001117d070e941e904072002406a00918$_sn:7$_ss:0$_st:1524832969982$_pn:2%3Bexp-session$ses_id:1524831079859%3Bexp-session$_prevpage:Welcome%3Atarife%3Aanasayfa%3Bexp-1524834769972
Host: localhost:4200
Pragma: no-cache
Referer: http://localhost:4200/
User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1
X-IMSI: 286026134103281
X-MSISDN: 905499914581
Request URL : http://localhost:4200/sockjs-node/info?t=1524831359435
I need to take X-IMSI and X-MSISDN parameters.
Following my comment : you could create a service that is in charge of handling all of your headers. That's also a good practice : you centralize the logic of a feature.
Here is an instance of a service that can do that. It can create JSON headers, append new headers to the list, reset them ... See for yourself.
import { Injectable } from '#angular/core';
import { Headers } from '#angular/http';
#Injectable()
export class HeadersManagerService {
private headers: Headers;
constructor() {
this.resetHeaders();
}
resetHeaders() {
this.headers = new Headers();
}
newHeader(key, value) {
this.headers.append(key, value);
}
createJsonHeaders() {
this.resetHeaders();
this.headers.append('Content-Type', 'application/json');
}
getHeaders() {
return this.headers;
}
}
PS: Posting as an answer because it's too long for a comment.
Why don't you try like this
setHeaders() {
const headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
const options = new RequestOptions({ headers: headers });
console.log(options.headers);
// return options;
}
In angular if it is object, for example
obj{name:"ABC" , role:"Student"} then Object.keys(obj); will return headers
Related
I am getting this error when trying to connect to an API in flutter to get user data. The API is remote, the phone has connection to the internet, I'm using an android phone to build the APP.
this is the error.
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = address, port = 43798
for back end we are using PHP Laravel , but the API should be open to anyone who has the address at this point in development, so much so that the get request works both in Postman and in browser when calling.
As for the flutter function, this is the code being used.
Future<User> getUser(url) async {
print("here");
var params = {
"id": "01142",
};
Uri uri =
Uri.parse(url);
uri.replace(queryParameters: params);
final response = await http.get(
uri,
headers: <String, String>{
'Content-Type': 'application/json',
'Accept': "*/*",
'connection': 'keep-alive',
'Accept-Encoding': 'gzip, deflate, br',
'host': 'ipv4',
},
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
user = User.fromJson(jsonDecode(response.body));
print("NEW USER");
print(user);
return user;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load user');
}
}
According to back end Laravel isnt using SSL either, what might be the problem?
I already developed ionic 4 in my Mac. When trying to improve an app in ionic 3, my http.post (angular) calls in php is received as GET ($ _SERVER ['REQUEST_METHOD']). I discovered that my parameters are not being recognized in php.
* I read the other posts and none solved my problem
Thank you!
import { Http , Headers, RequestOptions} from '#angular/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
let parametros = JSON.stringify({
idtApostador: localStorage.getItem("idtApostador"),
});
let headers = new Headers(
{
'Content-Type' : 'application/json'
});
let options = new RequestOptions({ headers: headers });
return new Promise(resolve => {
this.http.post(url, parametros, options)
.timeout(15000)
.subscribe(data => {
})
})
I ask, I answer. :)
https instead of http.
Use
import { HttpClient } from '#angular/common/http';
Instead of HTTP
I'm implementing a JWT authentification and I got a problem with the authorization set in the header.
It's looking like the 'Authorization' header isn't set in the request.
I got 2 request send by the client, the first one, the Authorization header pass in the request :
// GET PROJECTS NAME
projects.getName = () => { // === projects.getName = function() { ... }
return $http.get(Global.url_api+'action=GETINFO&table=Projects');
}
Request in browser :
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi....
Host: *******-tpinst.fr
Origin: http://localhost:2000
Proxy-Connection: keep-alive
Referer: http://localhost:2000/
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
But my second request implemented as the same as the first one didn't pass this authorization header :
users.get = function(project){
return $http.get(Global.url_api+'action=GET&table='+project+'_users');
}
In the browser :
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: GET
Host: bouygues-tpinst.fr
Origin: http://localhost:2000
Proxy-Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
The authorization is set in main program :
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = 'Bearer
'+localStorage.getItem('tokenAPI');
}])
I set Allow origin in my server side with these lines :
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE,
OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
I'm a beginner in these security notions, please guide me on a good way
EDIT :
I just found a hint, in my api.php i got this line to send error 401 to client :
$Authorization = $_SERVER['HTTP_AUTHORIZATION'];
//Looking for authorization headers
if($Authorization){ ... }
else {
header('HTTP/1.0 401 Unauthorized'); //Give error code 401
echo 'Token not found in the header';
}
When i delete
header('HTTP/1.0 401 Unauthorized');
The Authorization pass in the header
Remove the $httpProvider.defaults.headers.common
instead implement an http interceptor
Try this
app.factory("authInterceptor", authInterceptor);
authInterceptor.$inject = ["$q"];
function authInterceptor($q) {
return {
// Add an interceptor for requests.
'request': function (config) {
// Default to an empty object if no headers are set.
config.headers = config.headers || {};
// Set the token
var token = localStorage.getItem('tokenAPI');
config.headers.Authorization = "Bearer " + token;
return config;
},
// Add an interceptor for any responses that error.
'responseError': function (response) {
// Check if the error is auth-related.
if (response.status === 401 || response.status === 403) {
}
return $q.reject(response);
}
};
}
app.config(["$httpProvider",
function ($httpProvider) {
//Registers the interceptor
$httpProvider.interceptors.push("authInterceptor");
}]);
And i think the re-arrangement of your scripts causes the issue, place your controller script in the bottom
something like this
And in your main.js remove the
var app = angular.module('App', ['ngMaterial', 'ngMessages']) because we placed it in the index.html
I've been trying to figure this out for almost a day, with no luck.
I have a simple http.post request:
import { Component } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/toPromise';
#Component({
selector: 'SendPost',
})
export class SendPostComponent {
constructor(
private http:Http,
) {}
private urlPost:string = 'www.mydomain.com/api/order.php'
private addToBasket() {
var data = {
foo: "bar",
foo1: "another"
}
var postData = JSON.stringify(data);
let headers = new Headers({'Content-Type': 'application/json'}); //x-www-form-urlencoded
headers.append('Access-Control-Allow-Methods', "GET, POST, OPTIONS");
let options = new RequestOptions({ headers: headers });
this.http.post(
this.urlPost,
postData,
options
)
.toPromise()
.then((res) => {this.extractData(res)});
}
private extractData(res: Response) {
console.log('extractData:', res);
}
}
I striped the API endpoint to absolute minimum: no .htacces, just the php file this simple code:
<?php print_r(json_encode($_REQUEST)); die; ?>
I keep getting an empty array in return. However, if I change the code like this:
var data2 = 'foo=bar&foo1=another'
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
Then the $_REQUEST objects gets my data. What am I missing?
PHP $_REQUEST is:
An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE
and $_POST
An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.
PHP can't parse "application/json" data, the workaround is php wrapper, by using "file_get_contents('php://input')" you can fetch the data from request entity body in this way:
$body = file_get_contents('php://input');
$data = json_decode($body);
print_r($data); // here is what you need
I'm getting a 401 when trying to access the laravel api from vuejs using axios.
It's the Laravel 5.4 out-of-the-box setup so I have no idea why it doesn't work.
Here is my code:
// routes -> api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return request->user();
});
// axios request
axios.get('/api/user').then(function (response) {
console.log(response);
console.log(response.status);
});
Request contains all the token stuff.. I think.
X-CSRF-TOKEN:uAW2t..
X-Requested-With:XMLHttpRequest
X-XSRF-TOKEN:eyJpdiI..
All response by request:
General
Request URL:http://localhost/public/api/user
Request Method:GET
Status Code:401 Unauthorized
Remote Address:[::1]:80
Response Headers
view source
Cache-Control:no-cache, private
Connection:Keep-Alive
Content-Length:28
Content-Type:application/json
Date:Wed, 22 Mar 2017 09:35:49 GMT
Keep-Alive:timeout=5, max=92
Server:Apache/2.4.23 (Win64) PHP/5.6.25
X-Powered-By:PHP/5.6.25
X-RateLimit-Limit:60
X-RateLimit-Remaining:57
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Cookie:XSRF-TOKEN=eyJpdiI6IjNBVHdDNWdsTnBYT3FUT1E5d1IxTmc9PSIsInZhbHVlIjoiY05JYW9LdDB3ek5FVjRWYkVEM21NQlFEQnNPdHI0Rk5MdWhKbFcrZU1qWFB5MGIyXC9oR1RQNGJkdTB6RmZ3SFp1OU04S0RpazYzZW5ZNUhVMng1VCtnPT0iLCJtYWMiOiIyZTQ5ZDdlYTgwYmMzZTYxYjMzMjljMmNlMDJlYWFlNTNkNzJkZmY5ZGVlMTQ5ZjlmZDM4NTYzOTc1MjIwYzhkIn0%3D; laravel_session=eyJpdiI6IkhcLzJKRDVDTHRDN1FWUjZicDdZaVJnPT0iLCJ2YWx1ZSI6IlJoTkVQWUQ5OWZuYUo4bmF1eHRMYWFlamZramhtTkpmMnYwbUlaaTV3ZENuWFJQZW9IcDZxbU5EQjJXSDY2a01WMHpjeHU3Uk9UOG44MzN3NmgxK2NBPT0iLCJtYWMiOiI4OWM1ZWI3YjIzMDg5MTAwYjc0YmZmZDE4OTY3MjU5OTNkZDdjYjY2MjU3NmFlNTE3NDE2NTVjYzBhY2Y4MzJmIn0%3D
DNT:1
Host:localhost
Referer:http://localhost/public/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
X-CSRF-TOKEN:uAW2tI8bags0CaQaYBKmbfdExoCVDnZlJb1sW9f4
X-Requested-With:XMLHttpRequest
X-XSRF-TOKEN:eyJpdiI6IjNBVHdDNWdsTnBYT3FUT1E5d1IxTmc9PSIsInZhbHVlIjoiY05JYW9LdDB3ek5FVjRWYkVEM21NQlFEQnNPdHI0Rk5MdWhKbFcrZU1qWFB5MGIyXC9oR1RQNGJkdTB6RmZ3SFp1OU04S0RpazYzZW5ZNUhVMng1VCtnPT0iLCJtYWMiOiIyZTQ5ZDdlYTgwYmMzZTYxYjMzMjljMmNlMDJlYWFlNTNkNzJkZmY5ZGVlMTQ5ZjlmZDM4NTYzOTc1MjIwYzhkIn0=
If you authorising user to use api you have to have a token either in url or in authorisation header key. That token should be from api_token column in users table.
var token = 'exampleToken';
axios.get(
'/api/user?api_token=' + token, // here
{
headers:
{
'Authorization':'Bearer ' + token // or here
}
}
).then(...)
axios.get('/api/user',{headers:{
'Accept':'application/json',
'Authorization':'Bearer ' + window.localStorage.getItem('token_name_here')
'cache-control':'no-cache'
}).then(...)...