I have a decoupled drupal project with an angular 5 front end that is utilizing a restful api to store data. Because this API needed a key that we didn't want to expose we have created a restful endpoint in the Drupal code that acts as a sort of proxy. The front end hits Drupal, Drupal adds the key, hits the api, and then Drupal returns the api's response to the front end.
When I hit the API directly, I get clean JSON:
{"total":610,"results": .....
But when I use the proxy, I get encoded json:
"{\u0022total\u0022:610,\u0022results\u0022:[{\u0022_id\u0022:\u .....
My Angular request:
get(): Observable<RecipePreview[]> {
let encryptedAuthorizationString = 'BLAHBLAHBLAH';
const headers = new HttpHeaders()
.set("Content-Type", "application/json")
.set("X-CSRF-Token", this._HttpServiceService.csrfToken)
.set("Authorization", "basic " + encryptedAuthorizationString)
;
let u = this.filter.url();
return this._http.get(u,{headers})
.map(res => {
return res;
}
)
;
}
The Drupal RESTful endpoint code looks like this:
/**
* Responds to entity GET requests.
* @param $data
* @return \Drupal\rest\ResourceResponse
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function get() {
$url="BLAHBLAHBLAH";
$client = \Drupal::httpClient();
try {
$request = $client->request('GET', $url, [
'headers' => [
'Content-Type' => 'application/json',
'apikey' => "BLAH-BLAH-BLAH"
],
]);
$file_contents = $request->getBody()->getContents();
}
catch (RequestException $e) {
//An error happened.
$file_contents = "There was an error.";
}
\Drupal::logger('Proxy API')->debug($file_contents);
return new ResourceResponse($file_contents);
}
I'm pretty sure that ResourceResponse is doing something to the json, and there has got to be a way to tell it to not do it anymore? But how? Thoughts?
I'm also using the same final end point in a drupal content migration from source and I believe this formatting is causing issues with that as well.
Thanks so much for helping me out with this!