get headers with angular in second get.
In browser we write this:
http://localhost:4200
En console network apper the headers like this:
Accept-Ranges: bytes
Access-Control-Allow-Origin: *
Content-Length: `1428`
Content-Type: text/html; charset=UTF-8
Date: Thu, 05 Mar 2020 00:34:18 GMT
ETag: W/"54e-4HSDfsd4538gfdGFDgdf"
X-Powered-By: Express
With Angular I cant get those params, so, I do a second get with
httpClient.get('http://localhost:4200')
to set headers and then get headers params
But I dont know how put this params in header. So any one have idea?
I think that with a java can do that? maybe with a #Override. I dont know and then return headers with custom paramms
Some guide I will be grateuful
You need to build your headers and then pass it along to the get request:
Example:
const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
httpClient.get('<url>', { headers });
https://angular.io/guide/http#http-headers
Related
I'm trying to get the response header of a website and get the cookies that i can find inside. There is no problem, it's working when i start the request through a terminal with "node file.js".
But i'm launching the POST request through a local HTML page, so i used browersify for be able to launch a request from a client-side (or at least this is what i understood).
Then i'm using a CORS proxy to get around “No Access-Control-Allow-Origin header” problems. When i start the request from my local HTML page it's working and i can read the body but i'm not able to find the reponse header of the website and get the cookie that i need.
Here how my request looks like:
function connectionInfoConcert(account, psw, next){
console.log("-------------CREATE HEADER-------------\n")
var options = {
method: 'POST',
url: 'https://tranquil-thicket-71867.herokuapp.com/https://www.infoconcert.com/mon-infoconcert/connexion.html',
headers: {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Language':'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
'Cache-Control':'max-age=0',
'Connection':'keep-alive',
'Content-Length':'184',
'Content-Type':'application/x-www-form-urlencoded',
'origin': 'https://www.infoconcert.com',
'referer': 'https://www.infoconcert.com/mon-infoconcert/connexion.html'
},
form: {
origin:'',
username: account,
password: psw
}
};
console.log("-------------END HEADER-------------\n-----------START REQUEST-----------------------")
request(options, function (error, response, body) {
if (!error) {
console.log(response)
console.log(body)
console.log(response.headers['set-cookie'][0]); //obviously 'set-cookie' doesn't exist
}
else {
console.log(error)
console.log(response)
console.log("-------------ERROR------------")
return console.log("Something went wrong")
}
});}
https://www.infoconcert.com/mon-infoconcert/connexion.html is the website where i try to get the cookie
https://tranquil-thicket-71867.herokuapp.com is the CORS proxy that i'm using.
If some of you know how to be able to get the correct header it would be really nice !
Edit 1 :
The problem is when i do my request to "https://www.infoconcert.com/mon-infoconcert/connexion.html" i can find the cookie that i'm looking for in response.headers["set-cookie"].
But because i'm doing the request from a html page it's not working and i'm doing the request to "https://tranquil-thicket-71867.herokuapp.com/https://www.infoconcert.com/mon-infoconcert/connexion.html" but i can't find my cookie in the response.
Here the header of the response i got from "https://tranquil-thicket-71867.herokuapp.com/https://www.infoconcert.com/mon-infoconcert/connexion.html"
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: server,vary,cache-control,content-type,content-encoding,p3p,date,expires,pragma,connection,x-cache-info,x-final-url,access-control-allow-origin
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html; charset=UTF-8
Date: Thu, 03 May 2018 17:23:49 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
P3p: policyref="/w3c/p3p.xml", CP="NOI DSP COR NID CUR ADM DEV OUR BUS"
Pragma: no-cache
Server: Apache
Transfer-Encoding: chunked
Vary: Accept-Encoding,User-Agent
Via: 1.1 vegur
X-Cache-Info: not cacheable; response specified "Cache-Control: private"
X-Cors-Redirect-1: 302 https://www.infoconcert.com/mon-infoconcert/index.html
X-Cors-Redirect-2: 302 https://www.infoconcert.com/mon-infoconcert/connexion.html
X-Final-Url: https://www.infoconcert.com/mon-infoconcert/connexion.html
X-Request-Url: https://www.infoconcert.com/mon-infoconcert/connexion.html
So i think it's my proxy who doesn't forward the cookie that he gets.
If you need more details just ask.
Thanks you very much for your help
I'm trying to make a GET query using Fetch but I'm getting an error 404 when passing the Authorization.
I don't know why this error happens because the server responds well when I use a tool like Postman.
Authorization: Basic ...
method: GET
url: https://zammad.zonngo.com/api/v1/ticket_articles
When I use Javascript fetch API the error 404 appears.
OPTIONS https://zammad.zonngo.com/api/v1/ticket_articles 404 (Not Found)
There's my code:
const myHeaders = new Headers();
myHeaders.append('Authorization','Basic ...');
myHeaders.append('Content-Type','application/json');
fetch(URLTICKETS, {
method: 'GET',
headers: myHeaders
})
.then(response => {
console.log(response);
})
.then(error => {
console.log(error);
});
Would be nice if anyone can help me.
The GET method on the URL returns a 401 status code but the OPTIONS method actually returns a 404.
http OPTIONS https://zammad.zonngo.com/api/v1/ticket_articles
HTTP/1.1 404 Not Found
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html; charset=UTF-8
Date: Thu, 02 Nov 2017 01:37:59 GMT
Server: nginx/1.10.3 (Ubuntu)
Transfer-Encoding: chunked
X-Request-Id: 16f58319-2658-4b0e-824c-08ca68e8d401
X-Runtime: 0.003135
The OPTIONS is probably caused by a CORS preflight request which does not seem to be handled correctly by https://zammad.zonngo.com/.
https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
According to the image below
I'm trying to parse the (valid, according to JSONLint) JSON string with
obj = $parseJSON(data);
and receiving an error message of "Unexpected string".
Does anyone know what is the problem here?
As stated there is nothing wrong with $.parseJSON.
It's because you are using var_dump to output your json server side.
so the output include also the type and the length of your variable
string(1092) "mystring...
You should use a simple
echo $myjson;
It's sending back invalid JSON, and suspicious headers:
➜ ~ http GET http://www.borntoraiseheaven.org/categoria/lista/
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 257
Content-Type: text/html
Date: Thu, 30 Jul 2015 14:27:56 GMT
Keep-Alive: timeout=15, max=100
Server: Apache/2.2.16 (Debian)
Vary: Accept-Encoding
X-Powered-By: PHP/5.3.3-7+squeeze19
string(1092) "[ {"id_categoria":"188","descricao_categoria":"Envelopes"},
{"id_categoria":"187","descricao_categoria":"Tags"},
{"id_categoria":"186","descricao_categoria":null},
{"id_categoria":"184","descricao_categoria":null},
{"id_categoria":"160","descricao_categoria":"Adesivos"},
{"id_categoria":"161","descricao_categoria":null},
{"id_categoria":"183","descricao_categoria":"Postais"},
{"id_categoria":"169","descricao_categoria":"Folder\/Panfleto\/Flyer"},{"id_categoria":"158","descricao_categoria":null},
{"id_categoria":"164","descricao_categoria":"Cartazes"},
{"id_categoria":"178","descricao_categoria":null},
{"id_categoria":"166","descricao_categoria":"CD\/DVD"},
{"id_categoria":"167","descricao_categoria":"Encartes p\/ Mercados"},
{"id_categoria":"162","descricao_categoria":null},
{"id_categoria":"176","descricao_categoria":null},
{"id_categoria":"168","descricao_categoria":null},
{"id_categoria":"181","descricao_categoria":"Pastas"},
{"id_categoria":"163","descricao_categoria":null},
{"id_categoria":"182","descricao_categoria":null},
{"id_categoria":"177","descricao_categoria":"Kit de Amostras "} ]"
What you are showing is not valid json.
There should be nothing showing outside of [] including the external quotes and extra characters like "strong(1092)".
There is something wrong in your server output approach.
You can't selectively pull out part of the response and only validate that part.... the whole response body must validate
You have missed dot(.) In $parseJSON. You need to use $.parseJSON()
Purpose:
I (a javascript beginner) am trying to perform a Rest API call to a web-server (Splunk) get data of content-type json. Call is initiated by angularjs based webApp, the problematic code snippet is posted below. The problem is investigated using firebug and the response & header information is mentioned below.
Angular Code Snippet:
$scope.onClickButton = function (button) {
$http({
method: 'POST',
url: 'https://localhost:8089/servicesNS/admin/search/search/jobs/export',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Splunk ' + $scope.sessionKey
},
data: {search: button.query, output_mode: 'json'}
}).success(function (response) {
alert("Success");
}).error(function (response) {
alert("error");// alerted error
alert(response); // alerts 'undefined'
});
};
Response Object (captured by firebug)
{"preview":false,"offset":0,"result":{"_serial":"0", "_sourcetype":"mylogger", "splunk_server":"mohit-PC"}}
{"preview":false,"offset":1,"result":{"_serial":"1", "_sourcetype":"mylogger", "splunk_server":"mohit-PC"}}
{"preview":false,"offset":2,"result":{"_serial":"2", "_sourcetype":"mylogger", "splunk_server":"mohit-PC"}}
...
Response Header
Access-Control-Allow-Head... Authorization
Access-Control-Allow-Meth... GET,POST,PUT,DELETE,HEAD,OPTIONS
Access-Control-Allow-Orig... *
Cache-Control no-store, no-cache, must-revalidate, max-age=0
Connection Keep-Alive
Content-Type application/json; charset=UTF-8
Date Tue, 02 Dec 2014 13:00:34 GMT
Expires Thu, 26 Oct 1978 00:00:00 GMT
Server Splunkd
Transfer-Encoding chunked
Vary Authorization
access-control-allow-cred... true
x-content-type-options nosniff
x-frame-options SAMEORIGIN
Firebug Error
Error: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 1 of the JSON data fromJson#angular.js:1054:9
.
Questions
Q1. The status of response is - 200 OK, then why the error is thrown? Though it is apparent that the response text does not represent a json object or an array of json objects. The [] and commas are absent. The server cannot be configured to respond with a proper formatted data. It seems angular does a format verification and throws exception. Can this verification be avoided/bypassed?
Q2. Even though the error occurred, why the response object is 'undefined' in http.error method? If it were not, I could do string manipulations as a work around.
Say I got:
app.get('/json', function(req, res) {
res.set({
'content-type': 'application/json'
}).send('{"status": "0"}');
});
I'm trying to send the response as UTF-8 with the following with no success:
app.get('/json', function(req, res) {
// From Node.js Official Doc
// http://nodejs.org/api/http.html#http_http_request_options_callback
res.setEncoding('utf8');
res.set({
'content-type': 'application/json'
}).send('{"status": "0"}');
});
What is the correct way to set character encoding in Express?
You will probably want to explicitly add a charset to the end of your content-type string if you find it's not being set already by Express:
res.set({ 'content-type': 'application/json; charset=utf-8' });
The charset is not always set automagically and does need to be set to work correctly everywhere (i.e. with all browsers and all ajax libraries) or you can run into encoding bugs.
In Express 4.x specifically I've found that depending on the object you trying to return, it normally automatically returns with content-type: application/json; charset=utf-8 when you call res.json(someObject), however not always.
When calling res.json() on some objects it can return content-type: application/json (i.e. without the charset encoding!). I'm not actually sure what triggers this, other than it's something about the specific object being returned.
I've only noticed it because of automated tests which explicitly checked the headers and found it was missing the charset declaration on some responses (even though the content-type was still application/json).
Use res.charset: http://expressjs.com/api.html#res.charset
res.charset = 'value';
res.send('some html');
// => Content-Type: text/html; charset=value
However, JSON is UTF-8 by default so you don't need to set anything.
This worked for me
res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
Having similar issues I'm collecting Swedish characters from a database and outputting them as JSON object, node doesn't really care if json must be UTF-8 or not when the chars from the database isn't in UTF-8.. So assuming "you don't need to set anything" is false. Depending on what charsets you are working with.
Before you go to the trouble of manually setting header parameters, check what your server is already sending by default. In my case, I'm using a "serverless" cloud provided Node.js instance. Apparently, these are usually front-ended w/ NGINX which I assume is what sets some of this stuff based on default settings. ...I didn't need to res.set anything at all. Granted, I'm serving back HTML, ...just sayin - before you go fixin, make sure it's broke.
accept-ranges: bytes
accept-ranges: bytes
cache-control: private
content-encoding: gzip
content-type: text/html; charset=utf-8
date: Fri, 21 Dec 2018 21:40:37 GMT
etag: W/"83-xwilN/BBLLLAAAHHH/0NBLAH0U"
function-execution-id: 5thvkjd4wwru
server: nginx
status: 200
vary: accept-encoding, cookie, authorization
via: 1.1 varnish
x-cache: MISS
x-cache-hits: 0
x-cloud-trace-context: 18c611BBBBLLLLAAAHHH9594d9;o=1
x-powered-by: Express
x-served-by: cache-dfw18631-DFW
x-timer: S15BBLLLAAHHH.913934,VS0,VE3404