Home How to serve a json that was fetched via a POST call?
Reply: 1

How to serve a json that was fetched via a POST call?

kane
1#
kane Published in 2018-01-12 16:19:32Z

I have a button that invokes a POST call which retrieves a json response from the server. I'd like to open a new (chrome) browser tab with this json response.

This is what I have so far in angular

$http.post(url,data)
  .then(function(res) {
    $scope.toJSON = angular.toJson(res.data);
    var blob = new Blob([$scope.toJSON], { type:"application/json;charset=utf-8;" });

    var downloadLink = angular.element('<a></a>');
    downloadLink.attr('href',window.URL.createObjectURL(blob));
    downloadLink.attr('target','_blank');
    downloadLink[0].click();
  })

This code will open a new tab with the json in it, but it doesn't seem to be recognized as json. What I mean by this is that I have a chrome extension (JSONView), which will automatically pretty print any json. But it doesn't seem to pretty print this one.

If it matters, the new tab has an url that looks like this

blob:chrome-extension://knecfkbfhnkfajaonlnodhpjpbbpjfcp/c3b7e4dc-8209-4d0f-8f79-d8ba25e960a2

I've tried a bunch of different chrome extensions for viewing json and they all exhibit the same effect. It's possible the extensions can't process this "blob:chrome-extension://" page.

So what's the right way to open a json in a new tab?

Clarification I don't want to display this on the page. I want to open it in a new tab. I should mention that this is code within a Chrome Extension, not a standard web page

guest271314
2#
guest271314 Reply to 2018-01-12 16:39:12Z

Instead of using an extension you can use <pre> element and JSON.stringify()

fetch("https://gist.githubusercontent.com/guest271314/ffac94353ab16f42160e/raw/aaee70a3e351f6c7bc00178eabb5970a02df87e9/states.json")
.then(response => response.json())
.then(json => {
  document.querySelector("pre").textContent = JSON.stringify(json, null, 2)
})
<pre></pre>

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.428625 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO