Angular2 Http Response missing header key/values - angular2-http

I'm making an http.patch call to a REST API that is successful (Status 200) but not all the response headers key/values are being returned. I'm interested in the ETag key/value.
Here is a code snippet:
let etag:number = 0;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('If-Match', String(etag));
this.http.patch(
'http://example.com:9002/api/myresource/',
JSON.stringify(dto),
{headers: headers}
)
.subscribe(
(response:Response) => {
let headers:Headers = response.headers;
let etag:String = headers.get('ETag');
console.log(etag);
}
);
When making the same call with a REST Client (Postman), the response header contains:
Content-Type: application/hal+json;charset=UTF-8
Date: Mon, 01 Feb 2016 05:21:09 GMT
ETag: "1"
Last-Modified: Mon, 01 Feb 2016 05:15:32 GMT
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
X-Application-Context: application:dev:9002
Is the missing response header key/values a bug?
Can the issue be resolved with configuration?

This isn't an Angular issue, rather a CORS one. By definition, CORS will only return six "simple" headers: Cache-Control, Content-Language, Content-Type, Expires, Last-Modified and Pragma.
That's why you see the full set when using a REST client such as Postman, yet when calling from your Angular client, you'll only see the set limited by CORS.
To solve this, you'll need to add an Access-Control-Expose-Headers header along the following lines:
let headers = new Headers();
headers.append('Access-Control-Expose-Headers', 'etag');
let options = new RequestOptions({ headers: headers });
return this.http.get(uri, options).map(this.extractData).catch(this.catchError);
Note that you may need to augment the server side code to support the required exposed headers.
In my case (C#), I revised the EnableCors call (within WebApiConfig) to include "ETAG" in the list of exposed headers (the fourth parameter of the EnableCorsAttribute function).

Related

Wrong Content-Type in response in IErrorHandler

I would like to send response to my service in JSON format. I catch my custom errors in my custom behavior:
void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
XDocument errorMsg = XDocument.Parse("<errorMessage>" + error.Message + "</errorMessage>");
var jsonWriter = new JsonErrorBodyWriter(errorMsg);
fault = Message.CreateMessage(version, null, jsonWriter);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
HttpResponseMessageProperty prop = new HttpResponseMessageProperty();
prop.StatusCode = HttpStatusCode.Unauthorized;
prop.Headers.Add("Content-Type", "application/json; charset=utf-8");
prop.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8";
--Tried different ways to achieve this
fault.Properties.Add(HttpResponseMessageProperty.Name, prop);
}
But I get wrong content-type in response. And also I couldn't manage to write any custom header like :
prop.Headers.Add("Test", "Value");
Reponse:
HTTP/1.1 401 Unauthorized
Content-Type: application/xml; charset=utf-8
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Wed, 30 Sep 2020 08:41:15 GMT
Content-Length: 37
{"description":"Autorization Failed"}
What is wrong in my code?

How can I prevent RestSharp from double escaping a string containing end quotes?

I'm using RestSharp to consume a PHP based rest API (magento). I'm running into an issue where my request.Content contains a string escaped with backslashes. Like this: "\"mystringIsEscaped\"". It should just be a normal string "mystringIsNotEscaped".
The API does not give double quotes any specific treatment. A JSON response looks like this:
{
"value": 1
}
OR
"SomeValueAsJustString"
Here is my code so far:
// PART 1: Getting an Unauthorized Request Token
var request = new RestRequest("/rest/V1/integration/admin/token", Method.POST);
request.AddJsonBody(new {username = "this.adminUserName", password = "this.adminPassword"});
request.AddHeader("content-type", "application/json");
var _client = new RestClient(_url);
var _jsonSerializer = new JsonSerializer();
_client.AddDefaultHeader(_contentTypeHeaderWithUnderscore ? "Content_Type" : "Content-Type", "application/json");
_client.ClearHandlers(); // http://stackoverflow.com/questions/22229393/why-is-restsharp-addheaderaccept-application-json-to-a-list-of-item
_client.AddHandler("application/json", _jsonSerializer);
var response = _client.Execute(request);
response.Content is double escaped.
My raw response (using fiddler) looks like this:
HTTP/1.1 200 OK
Server: nginx/1.17.1
Date: Mon, 22 Jul 2019 12:38:44 GMT
Content-Type: application/json; charset=utf-8
Connection: keep-alive
Set-Cookie: PHPSESSID=873l8qhalaltets0tpa2s2sta1; expires=Mon, 22-Jul-2019 13:38:44 GMT; Max-Age=3600; path=/; domain=dev.myurlthatimhiding.org; HttpOnly
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
X-Frame-Options: SAMEORIGIN
Vary: Accept-Encoding
Content-Length: 34
"mysecuretokenstringthatimnotshowing"
How do I get RestSharp to not double encode, or more specifically, to properly handle the double quotes returned?
The response is generated on the PHP side. And as you can see with fiddler, the double quotes are coming from the PHP side and are not inserted by RestSharp.
The content type is the response generated by the PHP service is:
Content-Type: application/json; charset=utf-8
So it's supposed to be JSON.
Usually, JSON data is longer and structured. But it's also valid to return just a string. And in JSON, a string must be enclosed in double quotes.
The back slashes are an artifact of the debugger. I assume you are using Visual Studio. It displays all strings the way the would appear in your source code. In source code you would write:
var t = "\"mysecuretokenstringthatimnotshowing\"";
So the back slashes aren't contained, neither in the response nor in the string. It's just the debugger display.
It's a strange use of JSON. But it's valid. Just remove the double quotes at the beginning and at the end of the string and your fine.
Looks like Execute() gives you content as a string, which would be with the double quotes. To deserialize, you need to provide a type:
var response = request.Execute<string>();
var token = response.Content;
link

HTTP OPTIONS in Xamarin Forms

Getting "204 Status Code" as No Content
Here is a simple example of OPTIONS request:
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Options, new Uri("http://myapi.com"));
var response = await httpClient.SendAsync(request);
Just wondering why should you need to make one? OPTIONS is used to identify allowed request methods:
To find out which request methods a server supports, one can use curl
and issue an OPTIONS request:
curl -X OPTIONS http://example.org -i
The response then contains an Allow header with the allowed methods:
HTTP/1.1 200 OK
Allow: OPTIONS, GET, HEAD, POST
Cache-Control: max-age=604800
Date: Thu, 13 Oct 2016 11:45:00 GMT
Expires: Thu, 20 Oct 2016 11:45:00 GMT
Server: EOS (lax004/2813)
x-ec-custom-error: 1
Content-Length: 0
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

Load performance testing with Gatling and Content-Type

I am using gatling for load performance testing on a brand new API. It seems fairly easy and well documented but I am facing an issue as simple as POST a request with Content-Type set to 'application/vnd.api+json' on the Header. All works well when doing the GET stuff but when launching a POST test I get a
HTTP response:
status=
415 Unsupported Media Type
headers=
cache-control: [no-cache]
Content-Type: [application/vnd.api+json; charset=utf-8]
Date: [Fri, 08 Sep 2017 12:57:10 GMT]
Server: [nginx]
Vary: [Origin]
x-content-type-options: [nosniff]
x-frame-options: [SAMEORIGIN]
X-Request-Id: [ff993645-8e01-4689-82a8-2f0920e4f2a9]
x-runtime: [0.040662]
x-xss-protection: [1; mode=block]
Content-Length: [218]
Connection: [keep-alive]
body=
{"errors":[{"title":"Unsupported media type","detail":"All requests that create or update must use the 'application/vnd.api+json' Content-Type. This request specified 'application/json'.","code":"415","status":"415"}]}
Here is the scala code I am using for the http request:
object PostTokenGcm {
val token = exec {
http("TestAPI POST /tokens")
.post("/tokens")
.headers(Map("Authorization" -> testApiToken,
"Content-Type" -> "application/vnd.api+json",
"Accept" -> "application/vnd.api+json" ))
.body(StringBody(gcmTokenRequestBody)).asJSON
.check(status.is(201))
.check(bodyString.exists)
}}
It seems that it is not setting the Content-Type?
Thank you for any lead!
In your POST definition you're using asJSON. According to notes in documentation about request headers:
http("foo").get("bar").asJSON is equivalent to:
http("foo").get("bar")
.header(HttpHeaderNames.ContentType, HttpHeaderValues.ApplicationJson)
.header(HttpHeaderNames.Accept, HttpHeaderValues.ApplicationJson)
... so, headers set in:
.headers(Map("Authorization" -> testApiToken,
"Content-Type" -> "application/vnd.api+json",
"Accept" -> "application/vnd.api+json" ))
... get overwritten by asJSON to "application/json" (which is the value of HttpHeaderValues.ApplicationJson).

Luasocket custom headers, 404 turns to 301

My previous question was about fetching page title in lua using the socket.http module. The question lies here. Previously, youtube pages led me to a 404 error page. Based on MattJ's help, I put up custom HOST header for the request. This is what I did and what was the result:
Code
header = { host= "youtube.com" }
local result,b,c,h = http.request{ url = "http://www.youtube.com/watch?v=_eT40eV7OiI", headers = header }
print ( result, b, c, h )
for k,v in pairs(c) do print(k,v) end
Result
1 301 table: 0047D430 HTTP/1.1 301 Moved Permanently
x-content-type-options nosniff
content-length 0
expires Tue, 27 Apr 1971 19:44:06 EST
cache-control no-cache
connection close
location http://www.youtube.com/watch?v=_eT40eV7OiI
content-type text/html; charset=utf-8
date Sat, 28 Apr 2012 04:26:21 GMT
server wiseguy/0.6.11
As far as I was able to understand from this, the error is basically because of X-Content-Type-Options valued nosniff. Reading its documentation, I got to know that the only defined value, "nosniff", prevents Internet Explorer from MIME-sniffing a response away from the declared content-type.
Please help me so that I can use custom proxy and fetch the youtube(and some other sites, as mentioned in the previous question) title from their body. Here is the complete LUA file I currently have:
local http = require "socket.http"
http.PROXY="http://<proxy address here>:8080"
header = { host= "youtube.com" }
local result,b,c,h = http.request{ url = "http://www.youtube.com/watch?v=_eT40eV7OiI", headers = header }
print ( result, b, c, h )
for k,v in pairs(c) do print(k,v) end
I believe this line should be changed:
header = { host= "youtube.com" }
To:
header = { host= "www.youtube.com" }
After that, works for me.
The solution is to install luasec and to use ssl.https module to do the request.
Answered here by Paul Kulchenko!
Example:
-- luasec version 0.4.2
require("ssl")
require("https")
-- ssl.https.request(...)